zoukankan      html  css  js  c++  java
  • 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 = [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;
    }
  • 相关阅读:
    重写gallery 的 BaseAdapter
    excel数据导入DB
    更换 字体
    Android Activity跳转 Intent
    mpax5.0比mapx4.51多了些什么功能?
    [转载]INET控件的几点使用
    [转载]GIS基本概念集锦
    [转载]Microsoft.XMLHTTP对象
    等值线的绘制
    [转载]关于webbrowser,innet,xmlhttp获取网页源码的比较!
  • 原文地址:https://www.cnblogs.com/xitang/p/4126935.html
Copyright © 2011-2022 走看看