【问题标题】:Initializing a class. Can you see any problems with this?初始化一个类。你能看出这有什么问题吗?
【发布时间】:2010-10-07 12:08:48
【问题描述】:
-(id)init {

    if (self = [super init]) {

        self.name = [[NSString alloc] init];
        self.type = [[NSString alloc] init];
        self.phoneNumber = [[NSString alloc]init];
        self.webAddress = [[NSString alloc] init];

        NSMutableArray *pricesArray = [[NSMutableArray alloc] init];
        NSMutableArray *poolsArray = [[NSMutableArray alloc] init];
        self.prices = pricesArray;
        self.pools = poolsArray;

        [pricesArray release];
        [poolsArray release];

        //Create the address dictionaries
        NSMutableDictionary *addressItems = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"", KAddressStreet1Key, @"", KAddressStreet2Key, @"", KAddressBoroughKey, @"", KAddressCityKey, @"", KAddressCountyKey, @"", KAddressPostCodeKey, @"" ,KAddressCountryKey, nil];

        //Add dictionary to the array to contain address values
        self.address = addressItems;
        [addressItems release];

    }

    return self;
}

感谢EXC_BAD_ACCESS 错误,我目前正在进行大量调试..grr.

对于类 init 方法,上面的代码看起来是否合理且合乎逻辑?基本上,当我释放两个池(可变数组和字典)时,我得到了 EXC_BAD_ACCESS 错误。

【问题讨论】:

    标签: iphone objective-c cocoa-touch xcode


    【解决方案1】:

    您的属性是如何声明的?如果它们没有用retain 声明,那么您的大部分对象将在此方法结束时被释放。

    【讨论】:

    • 啊,抱歉。集合是“保留”,字符串是“复制”
    【解决方案2】:

    您在字符串属性的每个分配中都泄漏了对象。除此之外,我没有发现任何问题。 AddressXKeys 是如何定义的?

    【讨论】:

    • 好的,谢谢巴里。所以 alloc 是 +1 并且 copy 属性也是 +1 到我的保留计数?地址键是这样的:#define KAddressStreet1Key @"1address"
    • 是的,copy 属性会复制字符串并保留对副本的引用,因此原始文件丢失但保留计数为 +1。出于内存管理的目的,应将复制属性视为保留属性。
    • 免费提示:像这样的字符串常量的 Cocoa 模式是定义一个全局字符串引用。这样你就可以比较指针而不是使用 -[NSString isEqual:]。见stackoverflow.com/questions/538996/constants-in-objective-c/…
    猜你喜欢
    • 2011-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多