iOS MVC - Passing data back and forth to view controllers and model

后端 未结 1 1884
天涯浪人
天涯浪人 2021-01-24 13:58

I\'m new to iOS programming and having written a simple reminders style app, I\'m now rewriting it to implement the MVC model correctly as previously all my code was inside View

相关标签:
1条回答
  • 2021-01-24 14:40

    You can store the collection of Event in NSUserDefaults. Since its a custom class, you need to implement NSCoding protocol for serialization to NSUserDefaults.

    //Event.h
    
        @interface Event : NSObject<NSCoding>
    
        @property (nonatomic, copy)   NSString *name;
        @property (nonatomic, strong) NSDate *time;
        @property (nonatomic) NSInteger repeat;
    
        - (void)save;
        + (NSArray *)allEvents;
    
    //Event.m
    #define kSavedEvents @"SavedEvents"
    
    #pragma mark - Encoding
    - (void)encodeWithCoder:(NSCoder *)encoder
    {
        [encoder encodeObject:self.name  forKey:@"EventName"];
        [encoder encodeObject:self.time forKey:@"EventTime"];
        [encoder encodeObject:@(self.repeat) forKey:@"EventRepeat"];
    
    }
    
    #pragma mark - Decoding
    - (id)initWithCoder:(NSCoder *)decoder
    {
        self = [super init];
        if (self)
        {
            _name   = [decoder decodeObjectForKey:@"EventName"];
            _time   = [decoder decodeObjectForKey:@"EventTime"];
            _repeat = [[decoder decodeObjectForKey:@"EventRepeat"]integerValue];
    
        }
        return self;
    }
    

    You need to archive the data while storing to NSUserDefaults and unarchive when fetching

     (void)save
    {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
        NSData *savedData = [defaults objectForKey:kSavedEvents];
    
    
        NSMutableArray *savedEvents = [@[] mutableCopy];
    
        //Some events are already there in there
        if (savedData) {
            savedEvents = [[NSKeyedUnarchiver unarchiveObjectWithData:savedData]mutableCopy];
        }
    
        [savedEvents addObject:self];
    
        //Archiving the savedEvents to data
        NSData *newEventData = [NSKeyedArchiver archivedDataWithRootObject:savedEvents];
    
        [defaults setObject:newEventData forKey:kSavedEvents];
        [defaults synchronize];
    }
    
    + (NSArray *)allEvents
    {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSData *data = [defaults objectForKey:kSavedEvents];
        if (data)
        {
            return [NSKeyedUnarchiver unarchiveObjectWithData:data];
        }
        return nil;
    }
    

    Hope this will get you started.

    0 讨论(0)
提交回复
热议问题