0

I have a NSArray declared in .h file as

@interface ClassName : NSObject
{
NSArray *myArray;
}
@property (nonatomic, strong) NSArray *myArray;
@end

In the .m file here is how I have it.

@implementation ClassName
NSArray* myArray;

I am trying to access this in Swift as given below.

var x = ClassName().myArray

x is always nil.

4
  • 2
    And what's the init of ClassName? Does it initialize the myArray Commented Nov 9, 2022 at 12:02
  • @Larme, no I haven't initialized it. Commented Nov 9, 2022 at 12:03
  • 2
    Well, there’s your problem :) your Objective C class needs an –init method to initialize its objects with a new array instance set Commented Nov 9, 2022 at 12:06
  • 2
    In Objective-C, myArray is currently just declared. But nowhere we see a myArray = [[NSArray alloc] init]; (and I would have expected a NSMutableArray if you want to add values to it). Commented Nov 9, 2022 at 12:16

1 Answer 1

0

There are several issues with your Objective-C class. You've declared the myArray property (which is fine), but you've also added a public instance variable of the same name in the header file and you created a global variable (not instance variable) of the same name in the .m file. The following is what you should have:

In the .h file:

@interface ClassName : NSObject
@property (nonatomic, strong) NSArray *myArray;
@end

In the .m file:

@implementation ClassName

@end

That's it.

The next big issue is that you are accessing the myArray property but you never give it a value. This is why you always get nil.

This is no different than if you had a Swift class with an optional property that you never gave a value to.

Let's say you have the following Swift class:

class ClassName {
    var myArray: [Any]?
}

If you then did:

var x = ClassName().myArray

you would get nil just as you did using the Objective-C class. In both cases you need to create an instance of the class and assign an initial value to myArray.

var c = ClassName()
c.myArray = [ "Hi", "There" ]

Now you can access the array:

var x = c.myArray

BTW - assuming you want the array to hold specific types of values, you should update the property declaration in your Objective-C class.

For example:

@property (nonatomic, strong) NSArray<NSString *> *myArray;

if you wanted an array of NSString.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.