How to convert NSData to NSArray (or NSObject) - iphone

I did test this code, but it cause SIGABRT error.
NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:data]
NSData is plist data with xml format. This code works fine.
[urlData writeToFile:[self docPath] atomically:YES];
array = [[NSMutableArray alloc] initWithContentsOfFile:[self docPath]];
How can I change NSData to NSArray without file conversion?

This assumes you have populated NSString *filepath with the filepath of your saved data file.
NSPropertyListFormat format;
NSData *dataFromFile = [NSData dataWithContentsOfFile:fileNameWithPath];
NSArray *arrayFromFile = nil;
if (dataFromFile) {
arrayFromFile = [NSPropertyListSerialization propertyListFromData:dataFromFile
mutabilityOption:NSPropertyListMutableContainers
format:&format
errorDescription:NULL];
}
Hope that helps...

Related

loading Hierarchy in NSMutableData

Is there Hierarchy system in NSMutableData? If so, how do i load information in a hierarchy manner?
Example
//Create path to saving location
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSMutableData *gameData;
NSKeyedUnarchiver *decoder;
NSString *documentPath = [documentsDirectory stringByAppendingPathComponent:#"tierSave.dat"];
gameData = [NSData dataWithContentsOfFile:documentPath];
//end
//start loading
for(NSArray* firstData in gameData){
decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData:gameData];
int level1 = [decoder decodeIntegerForKey:level1];
}
//end
However in for(NSArray* firstData in gameData), the compiler tells me that gameData will not respond to count because it is a NSMutableData instead of NSMutableArray etc, How do i exactly re-implement the code above?
Saving:
Create a NSArray with your multiple NSData
Use NSKeyedArchiver to make a NSData from your NSArray
Loading:
Load a NSData from file
Use NSKeyedUnarchiver to extract the NSArray
Loop your NSArray
In code:
NSData *data0 = [NSData data]; // Data 1
NSData *data1 = [NSData data]; // Data 2
/////////// SAVE
// now make a array
NSArray *array = [NSArray arrayWithObjects:data0, data1, nil];
// now archive the data
NSData *archivedData = [NSKeyedArchiver archivedDataWithRootObject:array];
// archivedData contains now a binary plist with your archived array including your NSData objects
[archivedData writeToFile:path atomically:YES];
/////// LOAD
NSData *archivedDataFromFile = [NSData dataWithContentsOfFile:path];
NSArray *newArray = [NSKeyedUnarchiver unarchiveObjectWithData:archivedDataFromFile];
NSData *dataLoaded0 = [newArray objectAtIndex:0];

How used last value of variable when application closed?

I want to use an event like as i have some value in string and after storing value in string I have closed the application and now i again run that application. Now i want to use value of string which i save it in last time. How do that?
Thanks in advance...
you can use NSUserDefaults. you can refer following links
http://mobile.tutsplus.com/tutorials/iphone/nsuserdefaults_iphone-sdk/
http://www.cocoadev.com/index.pl?NSUserDefaults
http://www.icodeblog.com/2008/10/03/iphone-programming-tutorial-savingretrieving-data-using-nsuserdefaults/
[[NSUserDefaults standardUserDefaults] setObject:yourString forKey:yourKey]; // SET
yourString = [[NSUserDefaults standardUserDefaults] objectForKey:yourKey]; // GET
U should create a plist file .plist
step 1: #define DataFilePath before #implementation
#define DataFilePath [#"~/Documents/<fileName>.plist" stringByStandardizingPath]
step 2:create plist File than
if (![[NSFileManager defaultManager] fileExistsAtPath:DataFilePath])
{ NSData *data = [[NSData alloc] initWithContentsOfFile:[[NSBundle
mainBundle] pathForResource:#"" ofType:#"plist"]];
[data writeToFile:DataFilePath atomically:TRUE]; [data release]; } NSData *data = [NSData
dataWithContentsOfFile:DataFilePath]; NSLog(#"%#",DataFilePath);
NSPropertyListFormat format; NSArray *array =
[NSPropertyListSerialization propertyListFromData:data
mutabilityOption:NSPropertyListImmutable format:&format
errorDescription:nil];
step 3: save to plist file
NSString *path = [[CommonFunctions documentsDirectory]
stringByAppendingFormat:#"/%#",];
NSLog(#" file path = %#",path); [data writeToFile:path atomically:TRUE];

Convert nsdictionary to nsdata

have an app that can take a picture and then upload to a server. encoding it to base 64 and pass it thru a XMLRPC to my php server.
i want to take the NSDictionary info that is returned from UIImagePickerController delegate
-(void) imagePickerController:(UIImagePickerController *)imagePicker didFinishPickingMediaWithInfo:(NSDictionary *)info
and convert it to NSData so i can encode it.
so, how can i convert NSDictionary to an NSData?
You can use an NSKeyedArchiver to serialize your NSDictionary to an NSData object. Note that all the objects in the dictionary will have to be serializable (implement NSCoding at some point in their inheritance tree) in order for this to work.
Too lazy to go through my projects to lift code, so here is some from the Internet:
Encode
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:yourDictionary forKey:#"Some Key Value"];
[archiver finishEncoding];
[archiver release];
/** data is ready now, and you can use it **/
[data release];
Decode:
NSData *data = [[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath]];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
NSDictionary *myDictionary = [[unarchiver decodeObjectForKey:#"Some Key Value"] retain];
[unarchiver finishDecoding];
[unarchiver release];
[data release];
NSDictionary -> NSData:
NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:myDictionary];
NSData -> NSDictionary:
NSDictionary *myDictionary = (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithData:myData];
I know a bit too late, but just in case someone bumps into this same issue. UIImage is not serializable, but you can serialize it using the code:
if your image is JPG:
NSData *imagenBinaria = [NSData dataWithData:UIImageJPEGRepresentation(imagen, 0.0)];
// imagen is a UIImage object
if your image is PNG:
NSData *imagenBinaria = [NSData dataWithData:UIImagePNGRepresentation(imagen)];
// imagen is a UIImage object
The NSPropertyListSerialization class give you the most control over writing and reading of property lists:
NSDictionary *dictionary = #{#"Hello" : #"World"};
NSData *data = [NSPropertyListSerialization dataWithPropertyList:dictionary
format:NSPropertyListBinaryFormat_v1_0
options:0
error:NULL];
Read:
NSData *data = ...
NSPropertyListFormat *format;
NSDictionary *dictionary = [NSPropertyListSerialization propertyListWithData:data
options:0
format:&format
error:NULL];
Three options occur to me on this, two mentioned in other answers NSKeyedArchiver and PropertyList, there is also NSJSONSerialization that gave me the most compact data in a simple test.
NSDictionary *dictionary = #{#"message":#"Message from a cool guy", #"flag":#1};
NSData *prettyJson = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:nil];
NSData *compactJson = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:nil];
NSData *plist = [NSPropertyListSerialization dataWithPropertyList:dictionary
format:NSPropertyListBinaryFormat_v1_0
options:0
error:NULL];
NSData *archived = [NSKeyedArchiver archivedDataWithRootObject:dictionary];`
Size results for the different approaches smallest to largest
compactJson 46 bytes
prettyJson 57 bytes
plist 91 bytes
archived 316 bytes

read plist iphone sdk

I am trying to read a plist file using this -
NSData *data = [NSData dataWithContentsOfFile:SettingsFilePath];
NSPropertyListFormat format;
NSArray *array = [NSPropertyListSerialization propertyListFromData:data mutabilityOption:NSPropertyListImmutable format:&format errorDescription:nil];
but its not working.. is there any other way of doing this?
try with this way -
NSArray *arr= [[NSArray alloc] initWithContentsOfFile:plistPath];
Try + (id)arrayWithContentsOfFile:(NSString *)aPath to load it.

How can we create our own plist file in a Xcode project?

I want to create "UrlPaths.plist" file in my Application and also a dictionary with 4 or 5 objects. Please help me create a plist file and dictionary. And also read data from that plist file.
I want the plist to add the file to resources folder and i want to add Dictionary at that time also.i dont want pragmatical creation of plist but i want reading the data is pragmatically.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"plist.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSMutableDictionary *data;
if ([fileManager fileExistsAtPath: path]) {
data = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
}
else {
// If the file doesn’t exist, create an empty dictionary
data = [[NSMutableDictionary alloc] init];
}
//To insert the data into the plist
data[#"value"] = #(5);
[data writeToFile: path atomically:YES];
[data release];
//To retrieve the data from the plist
NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
int value1;
value1 = [savedStock[#"value"] intValue];
NSLog(#"%i",value1);
[savedStock release];
If you are about to create Plist without programmatically then follow these steps :
1. Right Click on Files in Left Pane and Select 'New File...' option.
2. Choose Resources from OS X tab.
3. An option for Property List is available.
4. Select an give an appropriate name.
This gets added to your project.
We can get simple understanding about plist as below
Now you can read this data as below
NSString *path = [[NSBundle mainBundle] pathForResource:#"Priority" ofType:#"plist"];
NSDictionary *dictPri = [NSDictionary dictionaryWithContentsOfFile:path];//mm
NSMutableArray *arrMarkets=[[NSMutableArray alloc] initWithArray:[dictPri valueForKey:#"List"]];
NSMutableArray *arrForTable=[[NSMutableArray alloc] init];
NSMutableArray *arrForTable1=[[NSMutableArray alloc] init];
for (NSDictionary *dict in arrMarkets)
{
NSString *strS1=nil;
strS1= [NSString stringWithFormat:#"%#",[dict valueForKey:#"Description"] ];
[arrForTable addObject:strS1];
}
NSLog(#"%#----------------- ",[arrForTable description]);
for (NSDictionary *dict in arrMarkets)
{
NSString *strS2=nil;
strS2= [NSString stringWithFormat:#"%#",[dict valueForKey:#"Name"] ];
[arrForTable1 addObject:strS2];
}
NSLog(#"%#----------------- ",[arrForTable1 description]);
create new plist file -
NSArray *Arr = [NSArray arrayWithObjects:obj1,obj2,nil];
NSData *data = [NSPropertyListSerialization dataFromPropertyList:Arr format:NSPropertyListXMLFormat_v1_0 errorDescription:nil];
[data writeToFile:PlistDataFilePath atomically:YES];
Read data from this plist file -
NSData *data = [NSData dataWithContentsOfFile:PlistDataFilePath];
NSPropertyListFormat format;
NSArray *array = [NSPropertyListSerialization propertyListFromData:data mutabilityOption:NSPropertyListImmutable format:&format errorDescription:nil];
you should read this great tut on plist files - http://www.edumobile.org/iphone/iphone-programming-tutorials/how-to-use-plist-in-iphone/