Tagged: data

iOS Core data tutorial, save and fetch an array.

1. Open up Xcode and create an empty iOS application (file->new->project, choose the Empty Application template under the iOS->Application section). Click next. Name your project CoreDataSaveArray (though this long name will haunt us later). Make sure to select “Use Core Data” and use ARC too.


2. From the project navigator select the CoreDataSaveArray.xcdatamodeld. This is the file that stores entity descriptions (templates for data objects basically), which make up the data model. Clicking the file will bring up the model editor window, pictured below. Click Add Entity on the bottom left to add an entity. Rename the entity Array. In the attributes section, click the + button to add an attribute to the Array entity. Name the attribute arrayData and set it’s type to string. Create another attribute called name, also a string.


3. Since this is project was started from an empty application, it has no xib or view controllers, so add a view controller and an xib. Click on File->New->File. Select Objective C Class from the Cocoa Touch section. Name your class CoreDataSaveArrayViewController and make sure it is a subclass of UIViewController. Select “With xib” and save the class in your project.

4. Now you need to set this view controller to be the root view controller. Your CoreDataSaveArrayAppDelegate.h should be edited to look like this:

[objc collapse=”False”]
#import <UIKit/UIKit.h>

//add this line
#import "CoreDataSaveArrayViewController.h"

//add this line
@class CoreDataSaveArrayViewController;

@interface CoreDataSaveArrayAppDelegate : UIResponder UIApplicationDelegate;

//add this line
@property (strong, nonatomic) CoreDataSaveArrayViewController *viewController;

@property (strong, nonatomic) UIWindow *window;
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
– (void)saveContext;
– (NSURL *)applicationDocumentsDirectory;


5. Add the lines indicated below to the application:didFinishLaunchingWithOptions method in the CoreDataSaveArrayAppDelegate.m.

[objc collapse=”False”]
– (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.

//add this line
_viewController = [[CoreDataSaveArrayViewController alloc]initWithNibName:@"CoreDataSaveArrayViewController" bundle:nil];

self.window.backgroundColor = [UIColor whiteColor];

//add this line
[self.window setRootViewController:_viewController];

[self.window makeKeyAndVisible];
return YES;

6. Create a user interface. Select the CoreDataSaveArrayViewController.xib and add three text fields, two buttons, a label for status output, and other labels to indicate usage as are needed to match the image below. I changed the status label’s background color to gray and the text to white. Create outlets in the CoreDataSaveArrayViewController.h for the text fields and label, as indicated in the image. Also add actions for the buttons.


7. Import the CoreDataSaveArrayAppDelegate.h to the CoreDataSaveArrayViewController.h.

[objc collapse=”False”]
#import UIKit/UIKit;

//add this
#import CoreDataSaveArrayAppDelegate;

@interface CoreDataSaveArrayViewController : UIViewController
@property (weak, nonatomic) IBOutlet UITextField *arrayNameTextField;
@property (weak, nonatomic) IBOutlet UITextField *arrayIndexTextField;
@property (weak, nonatomic) IBOutlet UITextField *arrayDataTextField;
@property (weak, nonatomic) IBOutlet UILabel *outputLabel;
– (IBAction)saveData:(id)sender;
– (IBAction)fetchData:(id)sender;

8. Implement the saveData and fetchData methods as below:

Save Data
[objc collapse=”False”]
– (IBAction)saveData:(id)sender {
//get instance of app delegate
CoreDataSaveArrayAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
//create managed object context
NSManagedObjectContext *context = [appDelegate managedObjectContext];
//create a managed object, which will be an instance of your entity Array
NSManagedObject *newArray;
//create the instance
newArray = [NSEntityDescription insertNewObjectForEntityForName:@"Array" inManagedObjectContext:context];
/* Create a string. We are actually going to create an comma separated string of array items, and save that to core data, as array is not a supported type in core data. Then we will make an array out of the string. We can make a string out of an array to if we want to save an array, as I have done in the viewDidLoad method.*/
[newArray setValue:_arrayDataTextField.text forKey:@"arrayData"];
[newArray setValue:_arrayNameTextField.text forKey:@"name"];
//clear the text fields
_arrayNameTextField.text = @"";
_arrayDataTextField.text = @"";
//save the data
NSError *error;
[context save:&error];
//output message
_outputLabel.text = @"Array saved";


Fetch Data
[objc collapse=”False”]
– (IBAction)fetchData:(id)sender {
//get instance of app delegate
CoreDataSaveArrayAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
//create managed object context
NSManagedObjectContext *context = [appDelegate managedObjectContext];
//get entity description
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Array" inManagedObjectContext:context];
//create a fetch request
NSFetchRequest *request = [[NSFetchRequest alloc]init];
[request setEntity:entityDesc];
//create predicate to filter request. We will be filtering our search by whatever is in the name text field.
NSPredicate *pred = [NSPredicate predicateWithFormat:@"(name = %@)", _arrayNameTextField.text];
[request setPredicate:pred];
//put the results in a managed object
NSManagedObject *matches = nil;
NSError *error;
NSArray *objects = [context executeFetchRequest:request error:&error];
//test the results of the search request
if ([objects count] ==0 ) {
_outputLabel.text = @"No Array by that name found";
} else {
matches = objects[0];
//get the arrayData (string) and add it to a sting object.
NSString *arrayString = [matches valueForKey:@"arrayData"];
//make an array from the string.
NSArray *array = [arrayString componentsSeparatedByString:@","];
//cast the index as an int
int theIndex = [_arrayIndexTextField.text intValue];
//output the results
if ([_arrayIndexTextField.text isEqualToString:@""]) {
//if there is no index number in the array index, just print the name of array and the string
_outputLabel.text = [NSString stringWithFormat:@"%@: %@",[matches valueForKey:@"name"],arrayString];

} else {
//else output the indexed item requested from our array
if (theIndex >= [array count]) {
_outputLabel.text = [NSString stringWithFormat:@"There is no %d item in %@", theIndex,[matches valueForKey:@"name"]];
} else {
_outputLabel.text = [NSString stringWithFormat:@"%@: Item at %@ is %@",[matches valueForKey:@"name"],_arrayIndexTextField.text, array[theIndex]];



9. Finally modify the viewDidLoad method as below to A. make the output label scale the font dynamically to fit all of the output text, and B. to add a sample array called groceries.

[objc collapse=”False”]
– (void)viewDidLoad
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.

//make the labels font adjust to fit all the data
_outputLabel.adjustsFontSizeToFitWidth = TRUE;

//create sample array called groceries
NSArray *sampleArray = @[@"bread", @"butter", @"milk", @"cheese", @"cereal"];
NSString * arrayAsString = [[sampleArray valueForKey:@"description"] componentsJoinedByString:@","];
CoreDataSaveArrayAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSManagedObject *newArray;
newArray = [NSEntityDescription insertNewObjectForEntityForName:@"Array" inManagedObjectContext:context];
[newArray setValue:arrayAsString forKey:@"arrayData"];
[newArray setValue:@"groceries" forKey:@"name"];

To test the app: start by entering groceries in the Array Name field. Then press the Fetch Data button. This should print all the “groceries” in the sample array. Try entering groceries in the Name field and 2 in the index field. This should return the third item in the groceries array. To make a new array, enter a new array name in the Array Name field. Add items, separated by commas, into the array data field. Tap save. This should save the data. You can search your new data as you did the groceries.

Here is the source code: CoreDataSaveArray.zip

Information found in iPhone IOS 6 Development Essentials by Neil Smyth was very helpful. It’s online for free, but you can buy a kindle edition or ebook, as I did.

Importing keyframe data to Maya

Use this python script to import keys to a single channel of each node in a group of selected objects. This setup, below, will import properly formatted keys to the .translateY attribute of selected objects.

This script will apply unique keys to each selected node if there is a corresponding number of data files in the source directory.

[py]import os
import maya.cmds as mc
## add path to keyframe data files – just the source directory that contains them.
## "ty", in line 13, refers to the Maya attribute channel of the selected objects. Modify this attribute as necessary.
objs= mc.ls(sl=True)
for subdir, dirs, files in os.walk(rootdir):
for thisFile, o in zip(files, objs):
file = open((os.path.join(rootdir, thisFile)), ‘r’)
lines = file.readlines()
for i in range(len(lines)):
mc.setKeyframe(o, at=’ty’, v=float(lines[i]), t=i, itt=’linear’, ott=’linear’)

See a sample of properly formatted keyframe data :

Also see http://oliverwolfson.com/extracting-raw-key-frame-data/

NEW! The script below will do the same as the script above, import After Effects Sound Keys keyframes, from .txt files, to Maya, but it will also take care of the formatting, so there is no need to run a shell script on your After Effects keyframes before importing.

This script will apply unique keys to each selected node if there is a corresponding number of data files in the source directory.

[py]##AE Import
import os
import maya.cmds as mc
## add path to keyframe data files – just the source directory that contains them.
## below is the attribute that you want to keyframe
theAttribute = ‘translateY’
count = 0
objs= mc.ls(sl=True)
for subdir, dirs, files in os.walk(rootdir):
dataFiles = [each for each in files if each.endswith(‘.txt’)]
for thisFile, o in zip(dataFiles, objs):
theName = objs[count]
count +=1
dataFile = open((os.path.join(rootdir, thisFile)), ‘r’)
lines = dataFile.readlines()
mylines = lines[10:-4]
for eachLine in mylines:
data = eachLine.split(‘\t’)
theFrame = data[1]
theValue = data[2]
mc.setKeyframe( o, v=float(theValue), at=theAttribute, t =float(theFrame))

Note: When pasting the keys from After Effects, be sure to use a code text editor like BB Edit or Text Wrangler. These apps will save your .txt files with UNIX line returns which is necessary to make this script work properly.

Technically the line breaks are invisible, but using the ‘tr’ command, in a UNIX shell, you could display them as any character you like, eg:

cat /path/some/file.txt | tr ‘\n’ ‘U’

In the above example, if the input file uses UNIX style line returns, \n ,each line will have a U at the end.