Wednesday, April 22, 2015

Saving data in NSUserDefaults

Saving data in NSUserDefaults

If You want to save some details of user in device then you can use NSUserDefaults.
It just like SharedPreference or cookie.

To write data in NSUserDefaults use below code.

NSString *valueToSave = @"someValue";
[[NSUserDefaults standardUserDefaults] setObject:valueToSave forKey:@"myKey"];
[[NSUserDefaults standardUserDefaults] synchronize];

To read data from NSUserDefaults use below code.

NSString *savedValue = [[NSUserDefaults standardUserDefaults]
    stringForKey:@"myKey"];

Thursday, April 2, 2015

How to create Singleton in Objective c

How to create Singleton in Objective c

1)Add Class which inherits NSObject
2)Implement following in YourSingleton.h
                    
#import <foundation/Foundation.h>

@interface YourSingleton: NSObject {
    NSString *someProperty;
}

@property (nonatomic, retain) NSString *someProperty;

+ (id)sharedInstance;

@end
 
 
3)In YourSingleton.m
 
#import "YourSingleton.h"

@implementation YourSingleton

@synthesize someProperty;

#pragma mark Singleton Methods

+ (id)sharedInstance{
    static YourSingleton*sharedInstance= nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance= [[self alloc] init];
    });
    return sharedInstance;
}

- (id)init {
  if (self = [super init]) {
      someProperty = [[NSString alloc] initWithString:@"Default Property Value"];
  }
  return self;
}

- (void)dealloc {
  // Should never be called, but just here for clarity really.
}

@end
 
 
 
Its Done.....Now you can use it whenever you want. :)
 
 
 
Note : Do not user for creating UIkitcomponent because reference of instance of sigleton are never released....