简体   繁体   中英

local variables, NSArray, EXEC_BAD_ACCESS on initWithObjects

I have some arrays that I only need in my .M file, so I thought that I declare them in the interface brackets like so in MyViewController.m ( by this I am making them private variables, in Java C# lingo)

   @interface MyViewController () {
    NSArray *myArray; 
   }
   @end

   @implementation FilterViewController
   - (void)viewDidLoad
   {
      [super viewDidLoad];
      // This line throws  an error
      myArray = [NSArray arrayWithObjects: @"1", @"2","3", @"4", nil];

Now the last line throws an EXEC_BAD_ACCESS, and I don;t know why?

I am new to Objective C coming from C#.Net, I think what I did with my declaration is like declaring private variables, if thats incorrect I am eager to know the correct way of doing it. Thanks.

Generally you would use properties for something like this, but with ARC it wont matter.

But the problem you have here is with "3" instead of @"3" . "3" is an array of characters, while the @ is a literal which turns the array into an NSString. Since NSArray can only store objects, it crashes when you try to add a char*

Note that a better way to create the array would be to use the new "container literals":

myArray = @[@"1", @"2", @"3", @"4"];

Then the compiler would give an error message if you accidentally omit the @ (or generally if any of the collection elements is not an Objective-C object), instead of your application crash at runtime.

You are missing this symbol @ in this line. So you need to use this one @"3" .

很简单,您在"3"之前错过了@符号。

myArray = [NSArray arrayWithObjects: @"1", @"2",@"3", @"4", nil];

Not a direct answer, but you don't need to declare your private iVars in an extension, you could just put it straight in the implementation: eg

@interface FilterViewController {
    NSArray *myArray; 
}

Although a better solution would be to use a property, which you do declare in the extension:

@interface FilterViewController () {
    @property (copy, nonatomic) NSArray *myArray; 
}
@end

@implementation FilterViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.myArray = @[@"1", @"2",@"3", @"4"];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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