Dicas Objective-C

Download de página Web de modo assincrono
Web page download asynchronous mode

// you have declared receivedData in your class
	NSURLRequest *theRequest=[NSURLRequest requestWithURL:
[NSURL URLWithString:@"http://www.census.gov/main/www/rss/popclocks.xml"]];
	NSURLConnection *theConnection=[[NSURLConnection alloc]
initWithRequest:theRequest delegate:self];
	if (theConnection) {
		receivedData = [[NSMutableData data] retain];
	} else {
		// Inform the user that the connection failed.
// add these methods to the class
- (void)connection:(NSURLConnection *)connection
                              didReceiveResponse:(NSURLResponse *)response
    [receivedData setLength:0];
- (void)connection:(NSURLConnection *)connection
                                     didReceiveData:(NSData *)data
    [receivedData appendData:data];
- (void)connection:(NSURLConnection *)connection
                               didFailWithError:(NSError *)error
    [connection release];
    [receivedData release];
    NSLog(@"Connection failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSErrorFailingURLStringKey]);
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
    // received all data. do something
    [connection release];
    [receivedData release];

Formatting number

[NSNumberFormatter localizedStringFromNumber:[NSNumber

Lendo um dicionário de um arquivo
Reading Dictionary from File

NSString* dataFilename = [[NSBundle mainBundle]
                             pathForResource:@"seufile" ofType:@"plist"];
mydict = [[NSDictionary alloc] initWithContentsOfFile:dataFilename];

Writing to a plist file
Escrevendo num arquivo plist

[recordepts writeToFile:
               [[NSBundle mainBundle]pathForResource:@"recorde"
                                                    ofType:@"plist"] atomically:YES];

Criando uma permutação aleatória
Creating a random permutation

-(NSArray*) scramble:(int)len {
	NSMutableArray * a1 = [NSMutableArray arrayWithCapacity:len];
	NSMutableArray * a2 = [NSMutableArray arrayWithCapacity:len];
	for (int i = 0; i < len; i++) {
		[a1 addObject:[NSNumber numberWithInt:i]];
	for (int i = len; i > 0; i--) {
		int num = arc4random() % i;
		[a2 addObject:[a1 objectAtIndex:num]];
		[a1 removeObjectAtIndex:num];
	return a2;

Human readable date diff

Sometimes you have to express date differences in a human readable way: “2 hours ago”, “yesterday”, etc. How to do this in Objective-C?

Here’s a nice solution

    - (NSString *) dateToName:(NSDate*)dt withSec:(BOOL)sec {
        NSLocale *locale = [NSLocale currentLocale];
        NSTimeInterval tI = [[NSDate date] timeIntervalSinceDate:dt];
        if (tI < 60) {
          if (sec == NO) {
               return NSLocalizedString(@"just now", @"");
           return [NSString stringWithFormat:
                     NSLocalizedString(@"%d seconds ago", @""),(int)tI];
         if (tI < 3600) {
           return [NSString stringWithFormat:
                     NSLocalizedString(@"%d minutes ago", @""),(int)(tI/60)];
         if (tI < 86400) {
          return [NSString stringWithFormat:
                     NSLocalizedString(@"%d hours ago", @""),(int)tI/3600];
         NSDateFormatter *relativeDateFormatter = [[NSDateFormatter alloc] init];
         [relativeDateFormatter setTimeStyle:NSDateFormatterNoStyle];
         [relativeDateFormatter setDateStyle:NSDateFormatterMediumStyle];
         [relativeDateFormatter setDoesRelativeDateFormatting:YES];
         [relativeDateFormatter setLocale:locale];
         NSString * relativeFormattedString = 
                [relativeDateFormatter stringForObjectValue:dt];
         return relativeFormattedString;

Usando o clipboard
Using Clipboard


One thought on “Dicas Objective-C”

Deixe uma resposta