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 alloc] init];
    [
returnValue setObject:[NSNumber      numberWithFloat:3.5] forKey:@”x”];
    [
returnValue setObject:[NSNumber numberWithFloat:23.8] forKey:@”y”];
    return [
returnValue autorelease];
}  
Better:
PHP Code:
- (NSDictionary *)testVariableValues {
    
NSMutableDictionary *returnValue = [NSMutableDictionary dictionary];
    [
returnValue setObject:[NSNumber numberWithFloat:3.5] forKey:@”x”];
    [
returnValue setObject:[NSNumber numberWithFloat:23.8] forKey:@”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 *s = “”; for (int i = 0; i < 10000; i++) s = [s stringByAppendingString:@“G”];
    return 
s;
}  
Good:
PHP Code:
- (NSString *)tenThousandGs {
     
NSMutableString *s = [[NSMutableString alloc] init];
     for (
int i = 0; i < 10000; i++)
         [
s appendString:@“G”];
     return [
s autorelease];
}  
Best:
PHP Code:
- (NSString *)tenThousandGs {
}
NSMutableString *s = [NSMutableString string]; for (int i = 0; i < 10000; i++) [s appendString:@“G”]; return s;  

No comments:

Post a Comment