首页 > 代码库 > NSDictionary获取内容的crash

NSDictionary获取内容的crash

相关资料:http://stackoverflow.com/questions/14489071/nsdictionary-release-triggers-valueforkey-return-value-release

NSString *path = [self.dataPath stringByAppendingPathComponent:@"dummy.plist"];NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];NSString *dummyKeyValue = http://www.mamicode.com/[dict valueForKey:@"dummyKey"];// NSLog(@"%@",[NSString stringWithString:dummyKeyValue]);[dict release];NSString *anotherString = [dummyKeyValue lowercaseString];
当使用到dummyKeyValue时 挂掉。

背景:

  NSDictionary在获得里面的值后, 对Dict进行释放。此时value也全部释放了。 当有引用在使用该value时,就会野指针。

 

解决办法:

NSString *dummyKeyValue = http://www.mamicode.com/[[[dict valueForKey:@"dummyKey"] retain] autorelease];

 

进一步: 

写分类来代替valueForKey方法。该分类实现下面功能

1. 类型转换保护

2. 数据内存计数保护(如上面所说)

 

例子:

- (NSString *)stringAtPath:(NSString *)path{    NSObject * obj = [[[self objectAtPath:path]retain]autorelease];    if ( [obj isKindOfClass:[NSNull class]] )    {        return nil;    }    else if ( [obj isKindOfClass:[NSNumber class]] )    {        return [NSString stringWithFormat:@"%lld", [(NSNumber *)obj longLongValue]];    }    else if ( [obj isKindOfClass:[NSString class]] )    {        return (NSString *)obj;    }        return nil;}

 

NSDictionary获取内容的crash