How to convert cv::Mat object into NSArray? - objective-c

I write this conversion like this:
NSData *data = [NSData dataWithBytes:mat.data length:mat.elemSize() * mat.total()];
NSArray *array = [NSKeyedUnarchiver unarchivedObjectOfClass:[NSArray class] fromData:data error:nil];
However I get array = nil. What's wrong with this conversion?

Answered by berak
Converting OpenCV Mat to array (possibly NSArray)

Related

[__NSCFString count]: Unrecognized selector

I know this has been asked before, but there is no answer that I have found useful.
First off here is my code
// load the .csv file with all information about the track
NSError *error;
NSString *filepath = [[NSBundle mainBundle] pathForResource:#"file" ofType:#"csv" inDirectory:nil];
NSString *datastring1 = [NSString stringWithContentsOfFile:filepath encoding:NSUTF8StringEncoding error:&error];
NSArray *datarow = [datastring1 componentsSeparatedByString:#"\r"];
//fill arrays with the values from .csv file
NSArray *data_seg = [datarow objectAtIndex:0]; //segment number
NSArray *data_slength = [datarow objectAtIndex:1]; //strait length
NSArray *data_slope = [datarow objectAtIndex:2]; //slope
NSArray *data_cradius = [datarow objectAtIndex:3]; //circle radius
NSArray *data_cangle = [datarow objectAtIndex:4]; //circle angle
NSLog(#"%i", [data_seg count]);
Okay, so there is the code, and I read that is has something to do with autorelease, but I was not able to add a retain like NSArray *data_seg = [[datarow objectAtIndex:0] retain]
When I run the code, I get [__NSCFString count]: unrecognized selector sent to instance 0x9d1ad50
Any help is appreciated, I'm not good at programming, and I am very new.
componentsSeparatedByString method returns an NSArray of NSString. Every item that you extract from datarow array is an NSString and an NSString doesn't respond to 'count'. Your code starting at //fill arrays is incorrect. Every objectAtIndex call will return an NSString*.
This is another way of saying that the datatype for data_seg is NSString* (not NSArray*).
With the corrected code snippet, the problem is because data_seg is a string, and -count is not a method of NSString. It seems you think data_seg is an NSArray.
Look at the documentation for -[NSString componentsSeparatedByString:] and see what it returns -- strings! So you get back an array of strings. So what you want is:
NSString *data_seg = [datarow objectAtIndex:0]; //segment number
NSLog(#"my segment number is: %#", data_seg);

Converting array of xml elements to an array of floats?

I have the following problem:
I am parsing a XML file, that contains a few "chas" elements. I save them in an array - arrayBegin. How to convert every object of the array to float ? I am a newbie, so I am really sorry for the dumb question. Thanks in advance! Here is my code:
NSString *dayToString = [NSString stringWithFormat:#"http://pik.bg/TV/bnt1/02.04.2013.xml"];
NSURL *url = [NSURL URLWithString:dayToString];
NSData *webData = [NSData dataWithContentsOfURL:url];
// every <chas> element from the xml file
NSString *xPathQueryBegin = #"//elem/chas";
TFHpple *parserBegin = [TFHpple hppleWithXMLData:webData];
NSArray *arrayBegin = [parserBegin searchWithXPathQuery:xPathQueryBegin];
NSLog (#"%d", [arrayBegin count]);
By this:
NSMutableArray *floatArray=[NSMutableArray new];
for(NSString *string in arrayBegin){
floatArray[floatArray.count]=#([string floatValue]);
}

Multidimensional Arrays in Objective C

I have an NSDictionary filled with data. If this was php it might be accessed by  something like:
$data = $array['all_items'][0]['name'];
How do I do something similar in objective c? ($array would be an NSDictionary)
The equivalent code in Objective-C is:
id data = [[[array objectForKey:#"all_items"] objectAtIndex:0] objectForKey:#"name"];
Note that objectForKey: is a method of NSDictionary, and objectAtIndex: is a method of NSArray.
A shortcut in Xcode 4.5, using LLVM 4.1, is:
id data = array[#"all_items"][0][#"name"];
Also note that if "array" is an NSDictionary instance and you want to get an array of all values in the dictionary, you use the allValues method of NSDictionary:
id data = [array allValues][0][#"name"];
Of course, allValues returns an unsorted array, so accessing the array by index is not very useful. More typically, you'd see:
for (NSDictionary* value in [array allValues])
{
id data = value[#"name"];
// do something with data
}
Unfortunately the objective-c version is not as elegant syntactically as the PHP version:
NSDictionary *array = ...;
NSArray *foo = [array objectForKey#"all_items"];
NSDictionary *bar = [foo objectAtIndex:0];
NSString *data = [bar objectForKey#"name"];
For brevity, you can do this on a single line as:
NSString *data = [[[array objectForKey#"all_items"] objectAtIndex:0] objectForKey#"name"];
You should use it,
NSString *value = [[multiArray objectAtIndex:1] objectAtIndex:0];
You can look the question here

How to save an array with float values into a text file that is readable by Mac?

I want to save float values stored in an array into a text file and read the file directly on Mac. This is how I create the array:
dataArray = [[NSMutableArray alloc] init];
NSNumber *numObj = [NSNumber numberWithFloat:3.14];
[dataArray insertObject:numObj atIndex:0];
NSNumber *numObj = [NSNumber numberWithFloat:2.3];
[dataArray insertObject:numObj atIndex:1];
...
This is how I save the array:
NSData *savedData = [NSKeyedArchiver archivedDataWithRootObject:dataArray];
NSString *filePath = #"/Users/smith/Desktop/dataArray.txt";
[savedData writeToFile:filePath options:NSDataWritingAtomic error:nil];
When I open the file, the contents are just garbled letters. Instead, I want to make it something like this:
3.14
2.3
1.4
...
the program you've written saves the object representation as an array of NSNumbers, while
the result you want/expect is a text file separated by newlines.
to save those float values into a text file of that format, you could to this:
...
NSMutableString * string = [NSMutableString new];
[string appendFormat:#"%f\n", 3.14];
[string appendFormat:#"%f\n", 2.3];
NSError * error = nil;
BOOL written = [string writeToURL:url atomically:YES encoding:someEncoding error:&error];
...
You can use componentsJoinedByString: to make an in-memory representation first, and then write that representation into a file, like this:
NSString *fileRep = [dataArray componentsJoinedByString:#"\n"];
NSString *filePath = #"/Users/smith/Desktop/dataArray.txt";
[fileRep writeToFile:filePath options:NSDataWritingAtomic error:nil];
This assumes that the number of items is relatively small, because the string representation is created entirely in memory.
Reading back is not as nice as writing out, though: you start by reading back a string, theb split it to components using [fileRep componentsSeparatedByString:#"\n"], and then go through components in a loop or with a block, adding [NSNumber numberWithDouble:[element doubleValue]] for each element of your split.
You probably want to create an XML plist from it to make it human-readable:
[dataArray writeToFile:filePath atomically:YES];
This creates a property list, which is human-readable XML (except if the file already exists AND it's a binary plist, in this case the new plist will also be binary).

How to convert a JSON array into an NSArray

I've been having trouble finding out how to convert a JSON array into an NSArray.
I have a php script that creates an array that is converted into JSON which is then sent and stored into an NSString that looks like:
[1,2,3,4]
My problem is that I need to make that into an NSArray of ints. How would one do that?
Thanks!
You should look at the documentation of the NSJSONSerialization class.
You can hand it the NSData received from a remote call that is a string in JSON format and receive the array or dictionary it contains.
NSObject *o =[NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&error];
// other useful "options":
// 0
// NSJSONReadingMutableLeaves
// NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers
you should then check that o is of the type you expect for sanity purposes
If I wanted to quickly break that into an array I would do it like this:
NSString * jstring = #"[1,2,3,4]"; //your json string
jstring = [jstring stringByReplacingOccurrencesOfString:#"[" withString:#""];
jstring = [jstring stringByReplacingOccurrencesOfString:#"]" withString:#""];
NSArray * intArray = [string componentsSeparatedByString:#","];
//you could create your int from the array like this
int x = [[intArray objectAtIndex:0]intValue];
Import the SBJson in your project (drag and drop it)
#import "SBJson.h"
Then where you receive the JSON response from the php file
NSArray *array = [responseString JSONValue];