Wednesday, August 22, 2012

Một số chú ý về quản lý bộ nhớ trên Iphon/Ipad

Nguồn: http://congdongios.com/showthread.php?108

+ Khi sử dụng alloc/copy/new bạn phải release ngay khi sử dụng chúng xong, thông thừong hãy đặt chúng trong dealloc 

+ Nếu là biến cục bộ thì release ngay trước khi return

+ Nếu nó là 1 biến được return lại trong hàm, thì hãy autorelease nó

+ cố gắng sử dụng alloc và release bằng tay hơn là sử dụng autorelease, chỉ sử dụng autorelease khi phải return về giá trị



Fine:
PHP Code:
- (NSDictionary *)testVariableValues {
    
NSMutableDictionary *returnValue = [[NSMutableDictionary allocinit];
    [
returnValue setObject:[NSNumber      numberWithFloat:3.5forKey:@”x”];
    [
returnValue setObject:[NSNumber numberWithFloat:23.8forKey:@”y”];
    return [
returnValue autorelease];
}  
Better:
PHP Code:
- (NSDictionary *)testVariableValues {
    
NSMutableDictionary *returnValue = [NSMutableDictionary dictionary];
    [
returnValue setObject:[NSNumber numberWithFloat:3.5forKey:@”x”];
    [
returnValue setObject:[NSNumber numberWithFloat:23.8forKey:@”y”];
    return 
returnValue;
}  
Best:
PHP Code:
- (NSDictionary *)testVariableValues {
      return [
NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:3.5], @”x”, [NSNumber numberWithFloat:23.8], @”y”nil];
}  


Bad:
PHP Code:
- (NSString *)tenThousandGs {
    
NSString *“”; for (int i 010000i++) = [s stringByAppendingString:@“G”];
    return 
s;
}  
Good:
PHP Code:
- (NSString *)tenThousandGs {
     
NSMutableString *= [[NSMutableString allocinit];
     for (
int i 010000i++)
         [
s appendString:@“G”];
     return [
s autorelease];
}  
Best:
PHP Code:
- (NSString *)tenThousandGs {
}
NSMutableString *= [NSMutableString string]; for (int i 010000i++) [s appendString:@“G”]; return s;  

No comments:

Post a Comment