Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use NSCoder

I am developing iphone application.

I use NSCoder.

MyApplication.h

#define ITEMS_KEY @"items"
#define CATEGORIES_KEY @"categories"


#import <UIKit/UIKit.h>


@interface MyApplicationData : NSObject <NSCoding, NSCopying> {
    NSMutableArray* items;
    NSMutableArray* categories;
}

@property (nonatomic ,retain) NSMutableArray* items;
@property (nonatomic, retain) NSMutableArray* categories;


@end

Myapplication.m

#import "MyApplicationData.h"


@implementation MyApplicationData

@synthesize items;
@synthesize categories;

#pragma mark NSCoding
- (void)encodeWithCoder:(NSCoder *)aCoder{
  [aCoder encodeObject:items forKey:ITEMS_KEY];
  [aCoder encodeObject:categories forKey:CATEGORIES_KEY];
}

-(id)initWithCoder:(NSCoder *)aDecoder{
  if(self = [super init]){
    self.items = [aDecoder decodeObjectForKey:ITEMS_KEY];
    self.categories = [aDecoder decodeObjectForKey:CATEGORIES_KEY];
  }
  return self;
}

#pragma mark -
#pragma mark NSCopying
-(id)copyWithZone:(NSZone *)zone{
  MyApplicationData* copy = [[[self class]allocWithZone:zone]init];
  items = [self.items copy];
  categories = [self.categories copy];
  return copy;
}

@end

But warnning.

'NSCoder' may not respond to '-decodeDataObjectForKey'

How to use NSCoder?

like image 841
marcy Avatar asked Nov 09 '09 15:11

marcy


People also ask

What is an NSCoder?

NSCoder declares the interface used by concrete subclasses to transfer objects and other values between memory and some other format. This capability provides the basis for archiving (storing objects and data on disk) and distribution (copying objects and data items between different processes or threads).

What is NSCoding Swift?

The NSCoding protocol declares the two methods that a class must implement so that instances of that class can be encoded and decoded. This capability provides the basis for archiving (where objects and other structures are stored on disk) and distribution (where objects are copied to different address spaces).

What is Nssecurecoding?

A protocol that enables encoding and decoding in a manner that is robust against object substitution attacks.

What is Nsobject in iOS?

The root class of most Objective-C class hierarchies, from which subclasses inherit a basic interface to the runtime system and the ability to behave as Objective-C objects. iOS 2.0+ iPadOS 2.0+ macOS 10.0+ Mac Catalyst 13.1+ tvOS 9.0+ watchOS 2.0+


1 Answers

Use -decodeObjectForKey: and read the documentation.

like image 71
Dave DeLong Avatar answered Oct 05 '22 21:10

Dave DeLong