简体   繁体   English

奇怪的BAD_ACCESS异常iOS

[英]Strange BAD_ACCESS exception iOS

I have a property (noARC) 我有财产(noARC)

@property (nonatomic, retain) NSString *itemUUID;

and an initialization 和初始化

- (void) viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (_itemUUID) {
        [self updateViews];
    } else {
       _itemUUID = [[EADataManager sharedInstance] generateUuidString];
        NSLog(@"%@", _itemUUID);
    }
}

The UUID generation method is UUID生成方法是

- (NSString *)generateUuidString
{
    CFUUIDRef UUID = CFUUIDCreate(kCFAllocatorDefault);
    NSString *uuidString = (NSString *)CFUUIDCreateString(kCFAllocatorDefault, UUID);
    [uuidString autorelease];
    CFRelease(UUID);
    return uuidString;
}

and I try to use this property in a very simple way in another method: 并且我尝试在另一种方法中以非常简单的方式使用此属性:

- (IBAction)submitButton:(id)sender
{
    if ([nameField.text length] > 3)
    {
        NSLog(@"%@", _itemUUID);
        NSDictionary *changedData = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:nameField.text, priceField.text, quantityField.text, nil] forKeys:[NSArray arrayWithObjects: @"Name", @"Price", @"Quantity", @"UUID", nil]];
    }
}

So on the second NSLog there is an exception BAD_ACCESS . 因此,在第二个NSLog有一个异常BAD_ACCESS Can't understand my fault. 无法理解我的错。

Your generateUuidString is returning an autorelease value, so your viewDidAppear should retain it (which you can do by using the setter, self.itemUUID = ... ). 您的generateUuidString返回的是autorelease值,因此您的viewDidAppear应该保留它(您可以使用setter self.itemUUID = ... )。

And kambala is correct as well, that you've also added three objects for your four keys of your dictionary. kambala也是正确的,您还为字典的四个键添加了三个对象。

You forgot to add your UUID to the object list in the dictionary, so number of objects and keys mismatches. 您忘记将UUID添加到字典的对象列表中,因此对象和键的数量不匹配。 Correct dictionary initialization: 正确的字典初始化:

NSDictionary *changedData = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:nameField.text, priceField.text, quantityField.text, _itemUUID, nil] forKeys:[NSArray arrayWithObjects: @"Name", @"Price", @"Quantity", @"UUID", nil]];

If you are not using ARC, this 如果您未使用ARC,则此

_itemUUID = [[EADataManager sharedInstance] generateUuidString];

is wrong, it assigns an object you do not own to an instance variable. 是错误的,它将您不拥有的对象分配给实例变量。 That object will go away when the autorelease pool is drained. 自动释放池耗尽后,该对象将消失。 Since you have declared a property, you should use it. 由于已声明属性,因此应使用它。

[self setItemUUID: [[EADataManager sharedInstance] generateUuidString]];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM