Showing posts with label iPhone. Show all posts
Showing posts with label iPhone. Show all posts

Feb 22, 2013

(XCode) How to search text in xib files

After several months of dev, a project could easily become ugly, probablly contains many used resources files(like pngs). It is easy to remove images that you know they are not using anymore, but that's not working for these looks unfamiliar. So i need to check their existence, it's simple to do a search in xcode, but xcode doesn't search in the xib files. Here is a line of command you can use in the terminal:

grep -i -r --include=*.xib "text you want to search" /your project's path

This command could search for all files (*.*).

Jun 27, 2012

(XCode) How to have lower simulator in Xcode 4.3 of Lion

The Xcode 4.3 does not have a simulator other than 5.1 and 4.3, but sometimes we need to test apps on the lower environment. So here is the trick: You need to have lower Xcode installation files, and copy the simulator folders to Xcode 4.3.

For exemple:
sudo mv /XCode file/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.1.sdk/ /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/

Nov 19, 2010

(iPhone)How to display different color text

There are several ways to display different color text in iOS device.
  1. Use multiple UILabel and each contains different font style.
  2. Use HTML tag and UIWebView.
  3. Use NSMutableAttributedString, this classe is added in iOS from 3.2, it needs Core Text to render rich text on the view. AliSoftware created a useful classe UIAttributedLabel which is an UILabel's subclass and supports NSMutableAttributedString. Check AliSoftware's github for more information.

Aug 19, 2010

(iPhone)How to customize UIAlertView

First solution is using addSubview which add subviews into an UIAlertView, just don't forget add newlines in the initWithTitle method's message to make sure you have enough space for subviews. Like :

[[UIAlertView alloc] initWithTitle:@"Title" message:@"\n\n\n" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil]

But this solution couldn't change UIAlertView's background, here is second solution that creates an UIAlertView's subclass, overrides several methods (setAlertText, alertText, drawRect, layoutSubviews and show), Joris Kluivers made an excellent sample, check it here : CustomAlert 

(iPhone)How to customize UINavigationBar's background

UINavigationBar has 2 methods to change it's style, barStyle and tintColor, but neither could set a background image for UINavigationBar.

Here is a solution to do that, add following code in your app delegate implementation file (.m) :

@interface UINavigationBar (MyCustomNavBar)
@end
@implementation UINavigationBar (MyCustomNavBar)
- (void) drawRect:(CGRect)rect {
    UIImage *barImage = [UIImage imageNamed:@"background_image.png"];
    [barImage drawInRect:rect];
}
@end

And change the "background_image.png" to the image what you want. This add a category in all UINavationBar used in your application, and you will see a fancy UINavigationBar.

Jul 28, 2010

(iPhone)How to debug EXC_BAD_ACCESS

In iOS programming, the EXC_BAD_ACCESS happens when application try to access some deallocated objects, but the Debugger Console usually display a simple message of "EXC_BAD_ACCESS", here is an useful solution to track the deallocated object.

- Set NSZombieEnabled = YES. With this argument, console will display a little bit more information, like "method : message sent to deallocated instance ...", sometime we can track the object in the method when it is easy to find.

- Set MallocStackLoggingNoCompact = 1, this argument allow to display alloc history of the object, for example: we got a message "message sent to deallocated instance 0x58448e0", type "info malloc-history 0x58448e0" in the console will display the allocate history of object 0x58448e0, which contains object allocation and deallocation, it is really useful to debug the incorrect release call.

To setup these 2 arguments, you should go to "Project"->"Edit Active Executable project name", add these 2 variables in "Variables to be set in the enviroment", names are "NSZombieEnabled" and "MallocStackLoggingNoCompact", values are "YES" and "1". And check the checkbox to active.

Don't forget remove these variables when you release your application.

May 17, 2010

(iPHone)How to retrieve value of "Bundle version"

Here is how to retrieve value of "Bundle version" in the project.plist using code.

NSString *version = [[[NSBundle mainBundle] infoDictionary] 
objectForKey:@"CFBundleVersion"];

(Iphone)How to move up an UIAlertView

Here is a trick to move your UIAlertView up on the screen.

UIAlertView * alert = [ [ UIAlertView alloc ] initWithTitle:@"Alert" 
message:@"Alert" 
delegate:self 
cancelButtonTitle:@"OK" 
otherButtonTitles:nil ];

alert.transform = CGAffineTransformTranslate(alert.transform, 
0.0, 100.0);

[ alert show ];

May 10, 2010

(iPhone)How to resolve "resources have been modified" when install an adhoc version

It's pretty weird my client has met this problem when he install an adhoc version on his iPhone. Arial Balkan posted a very useful solution, the idea is transforming the application (file .app) to an .ipa file which is executable in the iTunes.

Dec 29, 2009

(Objective-c)How to round a number

Here is a solution to round a float number:

NSString *pi = @"3.14159265";
int floatSize = 3;
NSDecimalNumber *numericValue = [NSDecimalNumber decimalNumberWithString:pi];
NSDecimalNumberHandler *roundingStyle = [NSDecimalNumberHandler 
decimalNumberHandlerWithRoundingMode:
NSRoundBankers scale:floatSize raiseOnExactness:NO raiseOnOverflow:NO 
raiseOnUnderflow:NO 
raiseOnDivideByZero:NO];
NSDecimalNumber *roundedNumber = [numericValue 
decimalNumberByRoundingAccordingToBehavior:
roundingStyle];

or

NSString *pi = @"3.14159265";
NSString *roundedNumber = [[NSString alloc] initWithFormat:
@"%.3f",[pi floatValue]];

Result: 3.142

Jul 10, 2009

(Objective-c) How to get MD5 hash string of a NSData


- (NSString*)dataMD5:(NSData*)data {
CC_MD5_CTX md5;

CC_MD5_Init(&md5);

CC_MD5_Update(&md5, [data bytes], [data length]);

unsigned char digest[CC_MD5_DIGEST_LENGTH];
CC_MD5_Final(digest, &md5);
NSString* s = [NSString stringWithFormat: 
@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
digest[0], digest[1],
digest[2], digest[3],
digest[4], digest[5],
digest[6], digest[7],
digest[8], digest[9],
digest[10], digest[11],
digest[12], digest[13],
digest[14], digest[15]];
return [s uppercaseString];
}

Feb 13, 2009

(Objective-C) How to sort an array

Here is an example to sort an array:

- (NSArray *) sortArray:(NSArray *)array :(BOOL)inAscending {
if (inAscending) {
return [array sortedArrayUsingSelector:@selector(compare:)];
}
else {
NSArray *ascendArray = [array sortedArrayUsingSelector:@selector(compare:)];
return [[ascendArray reverseObjectEnumerator] allObjects];
}
}

Dec 19, 2008

(iPhone) How to localize your application

iPhone 3G embeds several language setting, it is pretty cool to write an application which has multi language support. Here are 2 solutions we could use to set an UIButton bt's title:

First:
- Find the device default language

NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
NSArray* languages = [defs objectForKey:@"AppleLanguages"];
NSString* preferredLang = [languages objectAtIndex:0];

preferredLang returns the default language, it looks like: "en" for English, "fr" for French, "zh-Hans" for Chinese Simp, "zh-Hant" for Chinese Trad etc.

- Set up the text by different language

if ([preferredLang isEqualToString:@"en"]) {
[bt setTitle:@"Hello" forState:UIControlStateNormal];
}
else if ([preferredLang isEqualToString:@"fr"]) {
[bt setTitle:@"Bonjour" forState:UIControlStateNormal];
}
.......
else if ([preferredLang isEqualToString:@"zh-Hans"]) {
[bt setTitle:@"你好" forState:UIControlStateNormal];
}

Second:
- Create a strings file for your project (Add-New File-Strings File), Localizable.strings is a default strings file name, of course you can use the other names

- Make File Localizable: "Get Info" your strings file and click "Make File Localizable" on the left-bottom. You will see "English" shows on the Localizations list, and you can add the other languages by clicking "Add Localization". There are only 4 languages on the default list "English; French, Japnese and German". For the chinese, you should enter "zh_CN" for Chinese Simp and "zh_TW" for Chinese Trad, be careful it is different compare the first solution. After you have done this, there are several files under your strings file.

- Add the keys and values in the languages files. The format is:
in English
"hello" = "Hello !";

in French
"hello" = "Bonjour !";
etc.

Use the same keys for every language and just change the values. The iPhone will detect its language setting to load the right language file.

- Get the right text. If your strings file's name is Localizable, use NSLocalizedString(@"hello", nil) to get the value of "hello", if you use the other name, you should use NSLocalizedStringFromTable(@"hello", @"File name', nil) to return the text.

So the set bt's title, there is only one line of code:

[bt setTitle:NSLocalizedString(@"hello", nil) forState:UIControlStateNormal];

Oct 29, 2008

(iPhone) How to create an horizontal scrolling table

As we know the UITableView in the SDK allows to create a vertical scrolling table, but in my project i need a table which has horizontal scrolling. Why don't i create an UIScrollView, because i would like the header of table should be stable.

So what i do is create an UIScrollView which contains an UITableView, and the UIScrollView's contentsize equals the UITableView's size, then the UIScrollView won't do the vertical scrolling stuff.

There is one unconvenient thing when scroll verticaly, you should get the focus on the UITableView first, that means you should press on the screen to select a table cell and then scroll verticaly.

Oct 28, 2008

(iPhone) How to customize an UISwitch's text

In the UISwitch Class Reference, it said "The UISwitch class is not customizable". But i saw UISwitch's texts are not "ON/OFF" in some apps, in the UISwitch Class Reference doesn't contain such methods to change the defalut text. I just got the solution from iPhone Dev SDK Forum, someone posted these methods:

- (_UISwitchSlider *) slider {
return [[self subviews] lastObject];
}

- (UIView *) textHolder {
return [[[self slider] subviews] objectAtIndex:2];
}

- (UILabel *) leftLabel {
return [[[self textHolder] subviews] objectAtIndex:0];
}

- (UILabel *) rightLabel {
return [[[self textHolder] subviews] objectAtIndex:1];
}

- (void) setLeftLabelText: (NSString *) labelText {
[[self leftLabel] setText:labelText];
}

- (void) setRightLabelText: (NSString *) labelText {
[[self rightLabel] setText:labelText];
}

or

[(UILabel *)[[[[[[yourSwitch subviews] lastObject] subviews] objectAtIndex:2] subviews] objectAtIndex:0] setText:@"LeftText"];

[(UILabel *)[[[[[[yourSwitch subviews] lastObject] subviews] objectAtIndex:2] subviews] objectAtIndex:1] setText:@"RightText"];

_UISwitchSlider? what's that? I think you must have the same question? we can't find this class in the official reference documents. You can check by youself, it really exists in the official SDK, using [yourSwitch subviews] could show you that your UISwitch has an array of _UISwitchSlider, and then you can finally find your UISwitch contains 2 UILabel objects, and we can change their values.

I don't know if the future SDK will documentation these stuff, and i'm afraid there definitely has some other "hidden" methods, i can't understand why Apple doing this for developer, if they would like to release a SDK for public, they should release the whole documents.

Oct 8, 2008

(iPhone) How to get ${PRODUCT_NAME} value

${PRODUCT_NAME} presents as its name, it was defined in the info.plist, it is used for "Bundle display name", ''Bundle identifier", "Bundle name", and its default value is the project name. But you can change it using xcodebuild or XCode, how can we get its value in the code, here is an example:

NSDictionary *infoPList = [[NSBundle mainBundle] infoDictionary];
NSString *appName = [infoPList objectForKey:@"CFBundleDisplayName"];

appName is the value of "Bundle display name".

Sep 8, 2008

(iPhone) How to use Preference

Writing a simple data to preference:

CFStringRef textColorKey = CFSTR("defaultTextColor");
CFStringRef colorBLUE = CFSTR("BLUE");
// Set up the preference.
CFPreferencesSetAppValue(textColorKey, colorBLUE,
kCFPreferencesCurrentApplication);
// Write out the preference data.
CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication);

Reading a simple data from preference:

CFStringRef textColorKey = CFSTR("defaultTextColor");
CFStringRef textColor;
// Read the preference.
textColor = (CFStringRef)CFPreferencesCopyAppValue(textColorKey,
kCFPreferencesCurrentApplication);
// When finished with value, you must release it
// CFRelease(textColor);

To replace the exist key's value, just overwrite the values of key.

Aug 13, 2008

(iPhone) How to use SQLite

1. Add libsqlite3.dylib framwork in your project.

2. Add #import in your interface file.

3. You should create a .sql file, there are many ways to do it: you can create with you console by taping sqlite3 file.sql or you can create by coding in your project. In my case, i create the database dynamically, so i create the database file in my code, and i will post an example below.

4. Declare 2 variables in your interface file:
sqlite3 *database;
NSString *dbPath;
In you implementation file:
- (void) createTable {
dbPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"db.sql"];
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
NSString *createSql = @"CREATE TABLE test (text varchar(255))";
if (sqlite3_exec(database, [createSql cStringUsingEncoding:NSUTF8StringEncoding], NULL, NULL, NULL) == SQLITE_OK) {
NSLog(@"create table");
NSString *insertSql = @"INSERT INTO test (text) VALUES('fff')";
int testvalue = sqlite3_exec(database, [insertSql cStringUsingEncoding:NSUTF8StringEncoding], NULL, NULL, NULL);
if (testvalue == SQLITE_OK) {
NSLog(@"insert query ok");
}
else {
NSLog(@"error code %i", testvalue);
}
}
}
}

and this method will show you how to use the select query:
- (void) findRowNb {
NSString *selectSql = @"SELECT COUNT(*) FROM test";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(database, [selectSql cStringUsingEncoding:NSUTF8StringEncoding], -1, &statement, NULL) == SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
int count = sqlite3_column_int(statement, 0);
NSLog(@"row nb %i", count);
}
}
}

Jul 16, 2008

(IPhone) How to catch a button's click event

Here is an example:

//ViewBasedAppDelegate.h
#import

@class ViewBasedViewController;

@interface ViewBasedAppDelegate : NSObject {
UIWindow *window;

}

@property (nonatomic, retain) UIWindow *window;
-(void) catchButton;

@end

//ViewBasedAppDelegate.m
#import "ViewBasedAppDelegate.h"

@implementation ViewBasedAppDelegate
@synthesize window;

- (void)applicationDidFinishLaunching:(UIApplication *)application {
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(10.0, 90.0, 160.0, 40.0);
[button setTitle:@"Button" forState:UIControlStateNormal];
[button addTarget:(id)self action:@selector(catchButton)
forControlEvents:UIControlEventTouchUpInside];
[window addSubview:button];
[window makeKeyAndVisible];

}

- (void)catchButton{
NSLog(@"button pressed");

}

- (void)dealloc {
[window release];
[super dealloc];
}

@end