Dicas Objective-C

por Pedro Paulo · 1 comentário

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 
               numberWithUnsignedLongLong:myInteger]
               numberStyle:kCFNumberFormatterDecimalStyle];

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;
}
Compartilhe:
  • Print
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • email
  • Identi.ca
  • MySpace
  • Netvibes
  • PDF
  • StumbleUpon
  • Technorati
  • Twitter
  • Digg
  • HelloTxt
  • LinkedIn
  • Live
  • Posterous
  • Reddit
  • Tumblr
  • Yahoo! Bookmarks

Deixe seu comentário

{ 1 trackback }