0

I have a User Class that uses a saveuser() method whenever the application terminates. The User has two Arrays of Custom Classes that sub-class NSObject. Here is my encode method.

func encode(with aCoder: NSCoder) {
    aCoder.encode(self.firstName, forKey: coderKey.fName)
    aCoder.encode(self.lastName, forKey: coderKey.lName)
    aCoder.encode(self.bio, forKey: coderKey.bio)
    aCoder.encode(self.tags, forKey: coderKey.tags)
    aCoder.encode(self.organizations, forKey: coderKey.orgs)
    aCoder.encode(self.img, forKey: coderKey.img)
}

The app Crashes when encoding self.tags. I assume it will do the same with self.organizations because it is also an array of NSObjects and possibly with self.img because it is a UIImage. Here is the error I am getting.

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Social_Justice.Tag encodeWithCoder:]: unrecognized selector sent to instance 0x60000005efc0'

What should I do to resolve this issue? If you need to see any more code, just comment and i'll edit.

vadian
  • 274,689
  • 30
  • 353
  • 361
Gabe Spound
  • 146
  • 2
  • 14

2 Answers2

0

as David Berry commented on the original post. You have to Make sure any custom classes that you are trying to encode, also conform to NSCoder. They don't need to have archive paths, they just need to have the encode and decode functions.

Gabe Spound
  • 146
  • 2
  • 14
0

Answer:

  1. I assume the class name of the object inside the array self.tags and self.organizations are Tag and Organization

  2. Objective-C use a very different function calling style. If you see [ClassName/ObjectName methodName] which is somehow equivalent to ObjectName.function() style in Swift, let's put it in this way for the moment (the Swift compiler will be better in the future, and hopefully you will not see objctive-C warnings anymore when debugging)

  3. A selector is a term used by Objective-C, you could think this is a method. Therefore this unrecognized selector error warning tells you the code tried to call a method named encodeWithCode() that doesn't actually exist inside the object Tag and Organization (the NSCoder system knows how to encode an array, but has no idea to encode your own object inside Array)

  4. If you want to use the 5 concrete classes of the NSCoder system on an object, the object MUST conform the NSCoding protocol. It means the class (Tag and Organization) must implement init?(coder: NSCoder) and func encode(with: NSCoder)

  5. The 4 concrete class of NSCoder are NSArchiver, NSUnarchiver, NSKeyedArchiver, NSKeyedUnarchiver, and NSPortCoder.

Further Reading:

NSCoding / NSKeyed​Archiver By NSHipster

Or: (my favorite)

Apple Document NSCoder

Apple Document NSKeyedArchiver

Apple Document NSCoding

Or: (If those documents are still a bit confuse for you)

Hollemans M. 2016, iOS Apprentice Fifth Edition Tutorial 2 Checklist, pp 126 ~ pp 137

SLN
  • 4,772
  • 2
  • 38
  • 79