0

I have an class (model) written in Swift and I want to access it from Objective C class, but I can't.

To explain more, I have an array which is getting appended with dictionaries from that model written in Swift.

Model looks like this:

@objc class GoalPreviewModel: NSObject {
 var id : Int?
 var name : String?

 init(dictionary: NSDictionary)  {
     self.id = dictionary["id"] as? Int
     self.name = dictionary["name"] as? String
 }

}

This dictionary is filled fine by this model and everything works fine as long I'm accessing it from class written in Swift. The problem occurs when I try to access that array of dictionaries and access the properties. The statement bellow is working fine when I want to access name.

[_nameLabel setText:[(NSString*) [[AppState sharedInstance].arrayOfDicts objectAtIndex:idx] valueForKey:@"name"]];

But when I try to access valueForKey:@"id" it gives me an error like this "this class is not key value coding-compliant for the key id."

Can somebody help me out on this?

Thanks in advance!

Srdjan
  • 106
  • 10
  • 1
    Out of curiosity if you rename the property to something other than `id` does it work? – sbooth Dec 06 '16 at 13:03
  • @sbooth I tried that, but it doesnt work – Srdjan Dec 06 '16 at 13:45
  • Have you [seen this](http://stackoverflow.com/questions/24221407/can-a-swift-optional-int-int-be-exposed-to-objective-c-via-bridging)? – paulvs Dec 06 '16 at 13:53
  • It seems `Int` is bridged to the primitive `NSInteger` which cannot be nil (i.e. has no optionality). Also, as explained in the linked question and answer, an `Int?` cannot be bridged to an `NSNumber` because `NSNumber` is an object and could potentially store a non-integer value. – paulvs Dec 06 '16 at 14:01
  • @paulvs I have not, thanks! I'll try to fix it with that solution. – Srdjan Dec 06 '16 at 14:01
  • 1
    @paulvs Yes I see now, I'll try it now. Thanks! – Srdjan Dec 06 '16 at 14:01
  • @paulvs Yeah, that was the problem and its solved! Do you want to post the answer or you want me to do it? Thanks a lot! – Srdjan Dec 06 '16 at 14:33
  • I'm glad I could help @Srdja! I don't think I should answer this as there is already an excellent answer in the linked question, go vote that. I marked this as a duplicate. All the best! – paulvs Dec 06 '16 at 14:40
  • Complete answer for this is on [this link](http://stackoverflow.com/questions/24221407/can-a-swift-optional-int-int-be-exposed-to-objective-c-via-bridging) that @paulvs provided! – Srdjan Dec 06 '16 at 14:47

1 Answers1

0

you should make your properties (id and name) be public and try to access it without Key value coding on that way:

 [_nameLabel setText:(NSString*)[[AppState sharedInstance].arrayOfDicts 
                       objectAtIndex:idx]name]];
Marat Ibragimov
  • 1,076
  • 7
  • 7
  • Thanks for help, answer is on this [link](http://stackoverflow.com/questions/24221407/can-a-swift-optional-int-int-be-exposed-to-objective-c-via-bridging) – Srdjan Dec 06 '16 at 14:49