swiftobjective-cnsarray

How to read an Objective-C array in Swift? It's always returning nil


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.


Solution

  • 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.