Category Archives: Objective-C

Objective-C – Substring a NSString

There are 3 methods to substring a NSString.

NSLog([@"1234567890" substringFromIndex:4]);
NSLog([@"1234567890" substringToIndex:6]);
NSLog([@"1234567890" substringWithRange:NSMakeRange(3, 5)]);

  Continue reading Objective-C – Substring a NSString

Advertisements

Objective-C – Rounding float numbers

In Objective-C, you can use the ceil(), floor() and lroundf() functions to round a float number.

// ceil()
NSLog(@"ceil(1.4f)   : %f", ceil(1.4f));
NSLog(@"ceil(1.5f)   : %f", ceil(1.5f));

// floor()
NSLog(@"floor(1.5f)  : %f", floor(1.5f));
NSLog(@"floor(1.5f)  : %f", floor(1.5f));

// lroundf()
NSLog(@"lroundf(1.4f): %d", lroundf(1.4f));
NSLog(@"lroundf(1.5f): %d", lroundf(1.5f));

Continue reading Objective-C – Rounding float numbers

Objective-C – NSDictionary Example

NSDictionary is a useful object to store key-pair values just like HashMap in Java.

You can create and iterate a NSDictionary as follow

// Create a NSDictionary
NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", @"key3", nil];
NSArray *objs = [NSArray arrayWithObjects:@"obj1", @"obj2", @"obj3", nil];
NSDictionary *dict = [NSDictionary dictionaryWithObjects:objs forKeys:keys];
	
// Iterate it
for (id key in dict) {
	NSLog(@"key: %@   value:%@", key, [dict objectForKey:key]);
}

  Continue reading Objective-C – NSDictionary Example

Objective-C – How to Shuffle a NSMutableArray

You can use the following piece of code to randomize/shuffle the objects inside a NSMutableArray.

/* anArray is a NSMutableArray with some objects */
srandom(time(NULL));
NSUInteger count = [anArray count];
for (NSUInteger i = 0; i < count; ++i) {
	int nElements = count - i;
	int n = (random() % nElements) + i;
	[anArray exchangeObjectAtIndex:i withObjectAtIndex:n];
}

 

Update @ 2012-07-18: Suggestion from kimbebot

/* anArray is a NSMutableArray with some objects */
NSUInteger count = [anArray count];
for (NSUInteger i = 0; i < count; ++i) {
	int nElements = count - i;
	int n = (arc4random() % nElements) + i;
	[anArray exchangeObjectAtIndex:i withObjectAtIndex:n];
}

Done =)

Reference: StackOverflow – What’s the Best Way to Shuffle an NSMutableArray?

Objective-C – Display Date and Time Using NSDateFormatter

You can get the Date and Time in NSString using NSDateFormatter.

// Get current datetime
NSDate *currentDateTime = [NSDate date];

// Instantiate a NSDateFormatter
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

// Set the dateFormatter format
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

// Get the date time in NSString
NSString *dateInString = [dateFormatter stringFromDate:currentDateTime];

// Release the dateFormatter
[dateFormatter release];

Continue reading Objective-C – Display Date and Time Using NSDateFormatter

Objective-C – Convert NSString File Path to NSURL and Vice Versa

Convert NSString to NSURL

NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath];
/* OR */
NSURL *fileURL = [NSURL fileURLWithPath:filePath];

 

Convert NSURL to NSString

// The output string will have the file:// prefix
NSString *filePath= [fileURL absoluteString];

// The output string will have the file path only
NSString *filePath= [fileURL path];

 

Updated @ 2011-01-10: Thanks for the comments of Brandon and Antal.

Objective-C – Create a Static Class

Update @ 2012-08-07: As mentioned by Siby, the approach in this article may cause memory leak. Please try to use singleton as shown in the following link.
The Objective-C Singleton

 

Like Java, i would like to add a Static Class such that i could call static variables and static methods in any where.

In Objective-C, you can create a static variable using a static modifier.

For static method which is also known as class method, you can use the + sign instead of the – sign when declaring the method.

I have created a Utility class as follow.
Utility.h

@interface Utility : NSObject
+ (int)getNumber;
+ (void)setNumber:(int)number;
@end

 

Utility.m

#import "Utility.h"

@implementation Utility

static int number = 1;

+ (int)getNumber {
  return number;
}

+ (void)setNumber:(int)newNumber {
  number = newNumber;
}

+ (id)alloc {
  [NSException raise:@"Cannot be instantiated!" format:@"Static class 'ClassName' cannot be instantiated!"];
  return nil;
}

@end

 

Now i would like to get and set this static variable when loading HelloView. so I need to modify the HelloViewController.m.
HelloController.m

#import "Utility.h"

@implementation HelloController
...
- (void)viewDidLoad {
	[super viewDidLoad];
	NSLog(@"number = %d", [Utility getNumber]);
	[Utility setNumber:3];
	NSLog(@"number = %d", [Utility getNumber]);
}
...
@end

 

Run the application and check the Debugger Console.

2010-04-09 17:27:18.864 HelloWorld[10860:20b] number = 1
2010-04-09 17:27:18.874 HelloWorld[10860:20b] number = 3

 

Done =)

Update @ 2011-08-25: Add (id)alloc in Utility.m to avoid the class being instantiated. Thanks Liam. =)