Search code examples
iosdatabasesqliteprimary-keyviewdidload

How to dynamically create an auto increment primary key for item id in iOS?


I have a database storing list of items. I want to give id to each of these items and then fetch / update the details of item from DB.

I have used appcoda's sqlite DB manager and doing it in MVVM way.

So, how do i keep track of an item id or auto increment the id everytime? I tried to include id variable in viewDidLoad, but, it gets reinitialized everytime app loads. So primary key cant be unique.

How do i resolve the issue?

Thanks


Solution

  • you can use NSUserDefaults for your keys, it never gets destroyed until App is Uninstalled,

    suppose you have an id 'int itemID = 1' you can save it in NSUserDefaults like so,

    [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:itemID] forKey:@"id"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    

    every time you need to write these two lines when you want to update your id's count.

    Fetch value from UserDefauts

    int itemID = [[[NSUserDefaults standardUserDefaults]valueForKey:@"id"]intValue];