相关资料: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 = [dict valueForKey:@"dummyKey"];

// NSLog(@"%@",[NSString stringWithString:dummyKeyValue]);

[dict release];

NSString *anotherString = [dummyKeyValue lowercaseString];
当使用到dummyKeyValue时 挂掉。

背景:

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

 

解决办法:

NSString *dummyKeyValue = [[[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;
}

 

相关文章:

  • 2021-11-21
  • 2022-02-09
  • 2021-09-17
  • 2021-06-17
  • 2021-11-28
  • 2022-01-02
  • 2021-11-12
  • 2021-09-20
猜你喜欢
  • 2022-01-12
  • 2021-07-11
  • 2022-12-23
  • 2021-07-24
  • 2022-01-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案