Property 'myArray' not found on object of type 'MyVC *' Swift to Obj-C passing array Error

Viewed 83

This is my Swift File

@objcMembers class MyVC: NSObject {
    
    var myArray = [String]()
    
...
    

This is my ServiceControlVC.m Objective-C File

...
        MyVC *vc = [MyVC alloc];
        
        NSMutableArray *items = [NSMutableArray new];
        items = weakSelf.myModel.myModelArray;

        vc.myArray = items; // xxx this is the error point my compiler get crazy
... 

I am getting this error:
Property 'myArray' not found on object of type 'MyVC *'

Other properties seems okay, there is something missing point about object type or pointer for this arrray( my guess )

What should I do get rid of this compile error ? Can you tell me why this casting problems happens and how I define my MyVC swift file property :

var myArray = [String]() is a bad approach for this case ? Thanks

2 Answers

Your class needs to be a NSObject subclass and you could either:

  • use [String] type, but recognize that it is only exposing it as a NSArray <NSString *> * type to Objective-C and is employing copy semantics; or

  • alternatively, make your array a NSMutableArray type, not a Swift Array (but lose the great generic behavior of the Swift Array type).


Consider this type defined in Swift:

@objcMembers class Foo: NSObject {
    var strings: [String] = []
    var alternateStrings: NSMutableArray = []
}

And then consider this Objective-C behavior:

Foo *foo = [[Foo alloc] init];

NSMutableArray <NSString *> *items = [NSMutableArray new];
[items addObject:@"foo"];

foo.strings = items;
foo.alternateStrings = items;

[items addObject:@"bar"];

NSLog(@"myArray: %@", foo.strings);                // ["foo"]
NSLog(@"anotherArray: %@", foo.alternateStrings);  // ["foo", "bar"]

It comes down to the question of whether you really want to expose the array as mutable (probably not), or whether you are OK with the copy semantics that Swift [String] (aka Array<String>) exposes to Objective-C. (Frankly, even if the array is internally mutable, we often prefer to use copy semantics, anyway, to avoid unintended sharing and the problems that introduces.)


Regarding your compiler error about your property not being found, perhaps the issue is that when you change the Swift code, we need to compile before the {Module}-Swift.h header file will be regenerated.

Make it sub of : NSObject

@objcMembers class MyVC : NSObject {
   var myArray = [String]()
}
Related