I have a requirement to parse data files in "txf" format. The files may contain more than 1000 entries. Since the format is well defined like JSON, I wanted to make a generic parser like JSON, which can serialise and deserialise txf files.
On contrary to JSON, the mark up doesn't have a way to identify an object or an array. If an entry with same tag occurs, we need to consider it as an array.
# Marks the start of an object.
$ Marks the members of an object
/ Marks the end of an object
Following is a sample "txf" file
#Employees
$LastUpdated=2015-02-01 14:01:00
#Employee
$Id=1
$Name=Employee 01
#Departments
$LastUpdated=2015-02-01 14:01:00
#Department
$Id=1
$Name=Department Name
/Department
/Departments
/Employee
#Employee
/Employee
/Employees
I was able to create a generic TXF Parser using NSScanner. But with more entries the performance needs more tweaking.
I wrote the foundation object obtained as plist and compared its performance again the parser I wrote. My parser is around 10 times slower than plist parser.
While plist file size is 5 times more than txf and has more markup characters, I feel that there is a lot of room for optimization.
Any help in that direction is highly appreciated.
EDIT : Including the parsing code
static NSString *const kArray = #"TXFArray";
static NSString *const kBodyText = #"TXFText";
#interface TXFParser ()
/*Temporary variable to hold values of an object*/
#property (nonatomic, strong) NSMutableDictionary *dict;
/*An array to hold the hierarchial data of all nodes encountered while parsing*/
#property (nonatomic, strong) NSMutableArray *stack;
#end
#implementation TXFParser
#pragma mark - Getters
- (NSMutableArray *)stack{
if (!_stack) {
_stack = [NSMutableArray new];
}return _stack;
}
#pragma mark -
- (id)objectFromString:(NSString *)txfString{
[txfString enumerateLinesUsingBlock:^(NSString *string, BOOL *stop) {
if ([string hasPrefix:#"#"]) {
[self didStartParsingTag:[string substringFromIndex:1]];
}else if([string hasPrefix:#"$"]){
[self didFindKeyValuePair:[string substringFromIndex:1]];
}else if([string hasPrefix:#"/"]){
[self didEndParsingTag:[string substringFromIndex:1]];
}else{
//[self didFindBodyValue:string];
}
}]; return self.dict;
}
#pragma mark -
- (void)didStartParsingTag:(NSString *)tag{
[self parserFoundObjectStartForKey:tag];
}
- (void)didFindKeyValuePair:(NSString *)tag{
NSArray *components = [tag componentsSeparatedByString:#"="];
NSString *key = [components firstObject];
NSString *value = [components lastObject];
if (key.length) {
self.dict[key] = value?:#"";
}
}
- (void)didFindBodyValue:(NSString *)bodyString{
if (!bodyString.length) return;
bodyString = [bodyString stringByTrimmingCharactersInSet:[NSCharacterSet illegalCharacterSet]];
if (!bodyString.length) return;
self.dict[kBodyText] = bodyString;
}
- (void)didEndParsingTag:(NSString *)tag{
[self parserFoundObjectEndForKey:tag];
}
#pragma mark -
- (void)parserFoundObjectStartForKey:(NSString *)key{
self.dict = [NSMutableDictionary new];
[self.stack addObject:self.dict];
}
- (void)parserFoundObjectEndForKey:(NSString *)key{
NSDictionary *dict = self.dict;
//Remove the last value of stack
[self.stack removeLastObject];
//Load the previous object as dict
self.dict = [self.stack lastObject];
//The stack has contents, then we need to append objects
if ([self.stack count]) {
[self addObject:dict forKey:key];
}else{
//This is root object,wrap with key and assign output
self.dict = (NSMutableDictionary *)[self wrapObject:dict withKey:key];
}
}
#pragma mark - Add Objects after finding end tag
- (void)addObject:(id)dict forKey:(NSString *)key{
//If there is no value, bailout
if (!dict) return;
//Check if the dict already has a value for key array.
NSMutableArray *array = self.dict[kArray];
//If array key is not found look for another object with same key
if (array) {
//Array found add current object after wrapping with key
NSDictionary *currentDict = [self wrapObject:dict withKey:key];
[array addObject:currentDict];
}else{
id prevObj = self.dict[key];
if (prevObj) {
/*
There is a prev value for the same key. That means we need to wrap that object in a collection.
1. Remove the object from dictionary,
2. Wrap it with its key
3. Add the prev and current value to array
4. Save the array back to dict
*/
[self.dict removeObjectForKey:key];
NSDictionary *prevDict = [self wrapObject:prevObj withKey:key];
NSDictionary *currentDict = [self wrapObject:dict withKey:key];
self.dict[kArray] = [#[prevDict,currentDict] mutableCopy];
}else{
//Simply add object to dict
self.dict[key] = dict;
}
}
}
/*Wraps Object with a key for the serializer to generate txf tag*/
- (NSDictionary *)wrapObject:(id)obj withKey:(NSString *)key{
if (!key ||!obj) {
return #{};
}
return #{key:obj};
}
EDIT 2:
A sample TXF file with more than 1000 entries.
Have you considered using pull-style reads & recursive processing? That would eliminate reading the whole file into memory and also eliminate managing some own stack to keep track how deep you're parsing.
Below an example in Swift. The example works with your sample "txf", but not with the dropbox version; some of your "members" span over multiple lines. If this is a requirement, it can easily be implemented into switch/case "$" section. However, I don't see your own code handling this either. Also, the example doesn't follow the correct Swift error handling yet (the parse method would need an additional NSError parameter)
import Foundation
extension String
{
public func indexOfCharacter(char: Character) -> Int? {
if let idx = find(self, char) {
return distance(self.startIndex, idx)
}
return nil
}
func substringToIndex(index:Int) -> String {
return self.substringToIndex(advance(self.startIndex, index))
}
func substringFromIndex(index:Int) -> String {
return self.substringFromIndex(advance(self.startIndex, index))
}
}
func parse(aStreamReader:StreamReader, parentTagName:String) -> Dictionary<String,AnyObject> {
var dict = Dictionary<String,AnyObject>()
while let line = aStreamReader.nextLine() {
let firstChar = first(line)
let theRest = dropFirst(line)
switch firstChar! {
case "$":
if let idx = theRest.indexOfCharacter("=") {
let key = theRest.substringToIndex(idx)
let value = theRest.substringFromIndex(idx+1)
dict[key] = value
} else {
println("no = sign")
}
case "#":
let subDict = parse(aStreamReader,theRest)
var list = dict[theRest] as? [Dictionary<String,AnyObject>]
if list == nil {
dict[theRest] = [subDict]
} else {
list!.append(subDict)
}
case "/":
if theRest != parentTagName {
println("mismatch... [\(theRest)] != [\(parentTagName)]")
} else {
return dict
}
default:
println("mismatch... [\(line)]")
}
}
println("shouldn't be here...")
return dict
}
var data : Dictionary<String,AnyObject>?
if let aStreamReader = StreamReader(path: "/Users/taoufik/Desktop/QuickParser/QuickParser/file.txf") {
if var line = aStreamReader.nextLine() {
let tagName = line.substringFromIndex(advance(line.startIndex, 1))
data = parse(aStreamReader, tagName)
}
aStreamReader.close()
}
println(JSON(data!))
And the StreamReader was borrowed from https://stackoverflow.com/a/24648951/95976
Edit
see full code https://github.com/tofi9/QuickParser
pull-style line-by-line read in objective-c: How to read data from NSFileHandle line by line?
Edit 2
I rewrote the above in C++11 and got it to run in less than 0.05 seconds (release mode) on a 2012 MBA I5 using the updated file on dropbox. I suspect NSDictionary and NSArray must have some penalty. The code below can be compiled into an objective-c project (file needs have extension .mm):
#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
#include <map>
#include <vector>
using namespace std;
class benchmark {
private:
typedef std::chrono::high_resolution_clock clock;
typedef std::chrono::milliseconds milliseconds;
clock::time_point start;
public:
benchmark(bool startCounting = true) {
if(startCounting)
start = clock::now();
}
void reset() {
start = clock::now();
}
double elapsed() {
milliseconds ms = std::chrono::duration_cast<milliseconds>(clock::now() - start);
double elapsed_secs = ms.count() / 1000.0;
return elapsed_secs;
}
};
struct obj {
map<string,string> properties;
map<string,vector<obj>> subObjects;
};
obj parse(ifstream& stream, string& parentTagName) {
obj obj;
string line;
while (getline(stream, line))
{
auto firstChar = line[0];
auto rest = line.substr(1);
switch (firstChar) {
case '$': {
auto idx = rest.find_first_of('=');
if (idx == -1) {
ostringstream o;
o << "no = sign: " << line;
throw o.str();
}
auto key = rest.substr(0,idx);
auto value = rest.substr(idx+1);
obj.properties[key] = value;
break;
}
case '#': {
auto subObj = parse(stream, rest);
obj.subObjects[rest].push_back(subObj);
break;
}
case '/':
if(rest != parentTagName) {
ostringstream o;
o << "mismatch end of object " << rest << " != " << parentTagName;
throw o.str();
} else {
return obj;
}
break;
default:
ostringstream o;
o << "mismatch line " << line;
throw o.str();
break;
}
}
throw "I don't know why I'm here. Probably because the file is missing an end of object marker";
}
void visualise(obj& obj, int indent = 0) {
for(auto& property : obj.properties) {
cout << string(indent, '\t') << property.first << " = " << property.second << endl;
}
for(auto& subObjects : obj.subObjects) {
for(auto& subObject : subObjects.second) {
cout << string(indent, '\t') << subObjects.first << ": " << endl;
visualise(subObject, indent + 1);
}
}
}
int main(int argc, const char * argv[]) {
try {
obj result;
benchmark b;
ifstream stream("/Users/taoufik/Desktop/QuickParser/QuickParser/Members.txf");
string line;
if (getline(stream, line))
{
string tagName = line.substr(1);
result = parse(stream, tagName);
}
cout << "elapsed " << b.elapsed() << " ms" << endl;
visualise(result);
}catch(string s) {
cout << "error " << s;
}
return 0;
}
Edit 3
See link for full code C++: https://github.com/tofi9/TxfParser
I did some work on your github source - with following 2 changes I got overal improvement of 30% though the major improvement is from "Optimisation 1"
Optimisation 1 - based on your data came with with following work.
+ (int)locate:(NSString*)inString check:(unichar) identifier
{
int ret = -1;
for (int i = 0 ; i < inString.length; i++){
if (identifier == [inString characterAtIndex:i]) {
ret = i;
break;
}
}
return ret;
}
- (void)didFindKeyValuePair:(NSString *)tag{
#if 0
NSArray *components = [tag componentsSeparatedByString:#"="];
NSString *key = [components firstObject];
NSString *value = [components lastObject];
#else
int locate = [TXFParser locate:tag check:'='];
NSString *key = [tag substringToIndex:locate];
NSString *value = [tag substringFromIndex:locate+1];
#endif
if (key.length) {
self.dict[key] = value?:#"";
}
}
Optimisation 2:
- (id)objectFromString:(NSString *)txfString{
[txfString enumerateLinesUsingBlock:^(NSString *string, BOOL *stop) {
#if 0
if ([string hasPrefix:#"#"]) {
[self didStartParsingTag:[string substringFromIndex:1]];
}else if([string hasPrefix:#"$"]){
[self didFindKeyValuePair:[string substringFromIndex:1]];
}else if([string hasPrefix:#"/"]){
[self didEndParsingTag:[string substringFromIndex:1]];
}else{
//[self didFindBodyValue:string];
}
#else
unichar identifier = ([string length]>0)?[string characterAtIndex:0]:0;
if (identifier == '#') {
[self didStartParsingTag:[string substringFromIndex:1]];
}else if(identifier == '$'){
[self didFindKeyValuePair:[string substringFromIndex:1]];
}else if(identifier == '/'){
[self didEndParsingTag:[string substringFromIndex:1]];
}else{
//[self didFindBodyValue:string];
}
#endif
}]; return self.dict;
}
Hope it helps you.
Related
How to get Wi-Fi encryption mode in iOS without private libraries?
The code from the answer above has been posted originally on this website: http://www.codeproject.com/Articles/621213/Non-Standard-Way-to-Get-Inaccessible-Data-from-iOS
By the way, for this code to work you need to include the appropriate header files with #include <mach/mach.h> so that your compiler recognizes NDR_record_t ndr.
However, this whole setup did not actually return me the encryption mode of the current WiFi, but rather the configuration of AirPort (the variable key in the code from above needs to be set to NSString *key = #"Setup:/Network/Interface/en0/AirPort"; before). I tried different values instead of AirPort which I got from running $scutil in the Terminal of my Mac (such as Setup:/Network/Interface/en0/IPv4 or Setup:/Network/Interface/en0/Modem or from this website)
Hope that helps someone having similar issues...
For iOS 5:
aslmsg asl, message;
aslresponse searchResult;
int i;
const char *key, *val;
NSMutableArray *result_dicts = [NSMutableArray array];
asl = asl_new(ASL_TYPE_QUERY);
if (!asl)
{
DDLogCError(#"Failed creating ASL query");
}
asl_set_query(asl, "Sender", "kernel", ASL_QUERY_OP_EQUAL);
asl_set_query(asl, "Message", "AppleBCMWLAN Joined BSS:", ASL_QUERY_OP_PREFIX|ASL_QUERY_OP_EQUAL);
searchResult = asl_search(NULL, asl);
while (NULL != (message = aslresponse_next(searchResult)))
{
NSMutableDictionary *tmpDict = [NSMutableDictionary dictionary];
for (i = 0; (NULL != (key = asl_key(message, i))); i++)
{
NSString *keyString = [NSString stringWithUTF8String:(char *)key];
val = asl_get(message, key);
NSString *string = [NSString stringWithUTF8String:val];
[tmpDict setObject:string forKey:keyString];
}
[result_dicts addObject:tmpDict];
}
aslresponse_free(searchResult);
asl_free(asl);
For iOS 6:
#define kMachPortConfigd "com.apple.SystemConfiguration.configd"
-(NSDictionary *)getSCdata:(NSString *)key
{
if(SYSTEM_VERSION_LESS_THAN(#"6.0"))
{
// It does not work on iOS 5.*
return nil;
}
struct send_body {mach_msg_header_t header; int count; UInt8 *addr; CFIndex size0; int flags; NDR_record_t ndr; CFIndex size; int retB; int rcB; int f24; int f28;};
mach_port_t bootstrapport = MACH_PORT_NULL;
mach_port_t configport = MACH_PORT_NULL;
mach_msg_header_t *msg;
mach_msg_return_t msg_return;
struct send_body send_msg;
// Make request
CFDataRef extRepr;
extRepr = CFStringCreateExternalRepresentation(NULL, (__bridge CFStringRef)(key), kCFStringEncodingUTF8, 0);
// Connect to Mach MIG port of configd
task_get_bootstrap_port(mach_task_self(), &bootstrapport);
bootstrap_look_up2(bootstrapport, kMachPortConfigd, &configport, 0, 8LL);
// Make request
send_msg.count = 1;
send_msg.addr = (UInt8*)CFDataGetBytePtr(extRepr);
send_msg.size0 = CFDataGetLength(extRepr);
send_msg.size = CFDataGetLength(extRepr);
send_msg.flags = 0x1000100u;
send_msg.ndr = NDR_record;
// Make message header
msg = &(send_msg.header);
msg->msgh_bits = 0x80001513u;
msg->msgh_remote_port = configport;
msg->msgh_local_port = mig_get_reply_port();
msg->msgh_id = 20010;
// Request server
msg_return = mach_msg(msg, 3, 0x34u, 0x44u, msg->msgh_local_port, 0, 0);
if(msg_return)
{
if (msg_return - 0x10000002u >= 2 && msg_return != 0x10000010 )
{
mig_dealloc_reply_port(msg->msgh_local_port);
}
else
{
mig_put_reply_port(msg->msgh_local_port);
}
}
else if ( msg->msgh_id != 71 && msg->msgh_id == 20110 && msg->msgh_bits <= -1 )
{
if ((send_msg.flags & 0xFF000000) == 0x1000000)
{
CFDataRef deserializedData = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, send_msg.addr,send_msg.size0, kCFAllocatorNull);
CFPropertyListRef proplist = CFPropertyListCreateWithData(kCFAllocatorDefault, deserializedData, kCFPropertyListImmutable, NULL, NULL);
mig_dealloc_reply_port(msg->msgh_local_port);
mach_port_deallocate(mach_task_self(), bootstrapport);
mach_port_deallocate(mach_task_self(), configport);
mach_msg_destroy(msg);
NSDictionary *property_list = (__bridge NSDictionary*)proplist;
if(proplist)
CFRelease(proplist);
CFRelease(deserializedData);
CFRelease(extRepr);
return property_list;
}
}
mig_dealloc_reply_port(msg->msgh_local_port);
mach_port_deallocate(mach_task_self(), bootstrapport);
mach_port_deallocate(mach_task_self(), configport);
mach_msg_destroy(msg);
CFRelease(extRepr);
return nil;
}
Need some help with reading in lines of data from a text file using the fgets and string tokenization commands, which will then be used to create a linked list. I've followed some examples I've found on Stack Overflow and other tutorial websites, but still cannot get the read function below to work properly in my program, it just causes it to crash. The data file has lines like this:
Zucchini, Squash, pound, 2.19, 45
Yellow, Squash, pound, 1.79, 15
Based on everything I've read, I believe I have the necessary code, but obviously I'm missing something. Also, I commented out one of the fields (the one for float price) as I'm not sure what to use to copy the float value from the data, as I cannot treat it as a string (the integer value right below it seems to let me get away with it in my compiler).
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Struct for linked list node
struct produceItem
{
char produce[20];
char type[20];
char soldBy[20];
float price;
int quantityInStock;
struct produceItem *next;
};
// Function to read in data from file to
void read(struct produceItem **head)
{
struct produceItem *temp = NULL;
struct produceItem *right = NULL;
//char ch[3];
char line[50];
char *value;
FILE *data = fopen("RecitationFiveInput.txt", "r");
printf("Trying to open file RecitationFiveInput.txt\n");
if (data == NULL)
{
printf("Could not open file RecitationFiveInput.txt\n");
}
else
{
while(fgets(line, sizeof(line), data))
{
value = strtok(line, ", ");
strcpy(temp->produce, strdup(value));
value = strtok(NULL, ", ");
strcpy(temp->type, strdup(value));
value = strtok(NULL, ", ");
strcpy(temp->soldBy, strdup(value));
//value = strtok(NULL, ", ");
//strcpy(temp->price, strdup(value));
value = strtok(NULL, " \n");
strcpy(temp->quantityInStock, strdup(value));
temp->next = NULL;
if (*head == NULL)
{
*head = temp;
}
else
{
right = *head;
while(right->next != NULL)
{
right = right->next;
}
right->next = temp;
}
}
printf("Successfully opened file RecitationFiveInput.txt\n");
}
fclose(data);
return;
}
// Function to display the nodes of the linked list that contains the data from the data file
void display(struct produceItem *head)
{
int value = 1;
struct produceItem *temp = NULL;
temp = head;
printf("=============================================================================\n");
printf(" Item # Produce Type Sold By Price In Stock\n");
printf("=============================================================================\n");
if(temp == NULL)
{
return;
}
else
{
while(temp != NULL)
{
printf(" %d %s %s %s %lf %d\n", value, temp->produce, temp->type, temp->soldBy, temp->price, temp->quantityInStock);
value++;
temp = temp->next;
if(temp == NULL)
{
break;
}
}
}
return;
}
//Main function
int main()
{
int input = 0;
struct produceItem *head = NULL;
while(1)
{
printf("\nList Operations\n");
printf("=================\n");
printf("1. Stock Produce Department\n");
printf("2. Display Produce Inventory\n");
printf("3. Reverse Order of Produce Inventory\n");
printf("4. Export Produce Inventory\n");
printf("5. Exit Program\n");
printf("Enter your choice: ");
if(scanf("%d", &input) <= 0)
{
printf("Enter only an integer.\n");
exit(0);
}
else
{
switch(input)
{
case 1:
read(&head);
break;
case 2:
display(head);
break;
case 3:
//function
break;
case 4:
//function
break;
case 5:
printf("You have exited the program, Goodbye!\n");
return 0;
break;
default:
printf("Invalid option.\n");
}
}
}
return 0;
}
Never mind everyone, found the issue. The crashes were due to me not allocating memory for the temp pointer in the read me function.
I am facing a crash "Terminating app due to uncaught exception 'NSRangeException', reason:
'* -[NSSubrangeData subdataWithRange:]: range {8, 565316237} exceeds
data length 210204'"
If someone can help me in finding the solution of this.
-(NSData *) parseAtom:(MP4Atom **) pAtom fromData:(NSData *) data {
// Assume it all remains
NSData *remainingData = data;
// Data must not be nil
if( data != nil ) {
// Length must be at least 8 bytes
if( data.length > 8 ) {
// Read type and size
UInt32 size = [data uint32AtOffset:0];
NSString *type = [data fourByteStringAtOffset:4];
// The rest is data
NSData *atomData = [data subdataWithRange:NSMakeRange(8, size - 8)];
// Read the atom
MP4Atom *atom = [MP4Atom mp4AtomWithType: type data:atomData];
// Get the remaining data
if( size < data.length) {
remainingData = [data subdataWithRange:NSMakeRange(size, data.length - size)];
} else {
remainingData = nil;
}
// If we got a valid result...
if( atom != nil ) {
// ... and pAtom was not nil,
if( pAtom != nil ) {
// assign the atom
*pAtom = atom;
} else {
DDLogCritical( #"pAtom is nil in parseAtom:fromData:");
}
} else {
DDLogCritical( #"Failed to parse atom from data in parseAtom:fromData:");
}
} else {
DDLogCritical( #"data is too short (%d) expected at least 8 bytes in parseAtom:fromData:", data.length);
}
} else {
DDLogCritical( #"data is nil in parseAtom:fromData:");
}
return remainingData;
}
How to get Wi-Fi encryption mode in iOS without private libraries?
The code from the answer above has been posted originally on this website: http://www.codeproject.com/Articles/621213/Non-Standard-Way-to-Get-Inaccessible-Data-from-iOS
By the way, for this code to work you need to include the appropriate header files with #include <mach/mach.h> so that your compiler recognizes NDR_record_t ndr.
However, this whole setup did not actually return me the encryption mode of the current WiFi, but rather the configuration of AirPort (the variable key in the code from above needs to be set to NSString *key = #"Setup:/Network/Interface/en0/AirPort"; before). I tried different values instead of AirPort which I got from running $scutil in the Terminal of my Mac (such as Setup:/Network/Interface/en0/IPv4 or Setup:/Network/Interface/en0/Modem or from this website)
Hope that helps someone having similar issues...
For iOS 5:
aslmsg asl, message;
aslresponse searchResult;
int i;
const char *key, *val;
NSMutableArray *result_dicts = [NSMutableArray array];
asl = asl_new(ASL_TYPE_QUERY);
if (!asl)
{
DDLogCError(#"Failed creating ASL query");
}
asl_set_query(asl, "Sender", "kernel", ASL_QUERY_OP_EQUAL);
asl_set_query(asl, "Message", "AppleBCMWLAN Joined BSS:", ASL_QUERY_OP_PREFIX|ASL_QUERY_OP_EQUAL);
searchResult = asl_search(NULL, asl);
while (NULL != (message = aslresponse_next(searchResult)))
{
NSMutableDictionary *tmpDict = [NSMutableDictionary dictionary];
for (i = 0; (NULL != (key = asl_key(message, i))); i++)
{
NSString *keyString = [NSString stringWithUTF8String:(char *)key];
val = asl_get(message, key);
NSString *string = [NSString stringWithUTF8String:val];
[tmpDict setObject:string forKey:keyString];
}
[result_dicts addObject:tmpDict];
}
aslresponse_free(searchResult);
asl_free(asl);
For iOS 6:
#define kMachPortConfigd "com.apple.SystemConfiguration.configd"
-(NSDictionary *)getSCdata:(NSString *)key
{
if(SYSTEM_VERSION_LESS_THAN(#"6.0"))
{
// It does not work on iOS 5.*
return nil;
}
struct send_body {mach_msg_header_t header; int count; UInt8 *addr; CFIndex size0; int flags; NDR_record_t ndr; CFIndex size; int retB; int rcB; int f24; int f28;};
mach_port_t bootstrapport = MACH_PORT_NULL;
mach_port_t configport = MACH_PORT_NULL;
mach_msg_header_t *msg;
mach_msg_return_t msg_return;
struct send_body send_msg;
// Make request
CFDataRef extRepr;
extRepr = CFStringCreateExternalRepresentation(NULL, (__bridge CFStringRef)(key), kCFStringEncodingUTF8, 0);
// Connect to Mach MIG port of configd
task_get_bootstrap_port(mach_task_self(), &bootstrapport);
bootstrap_look_up2(bootstrapport, kMachPortConfigd, &configport, 0, 8LL);
// Make request
send_msg.count = 1;
send_msg.addr = (UInt8*)CFDataGetBytePtr(extRepr);
send_msg.size0 = CFDataGetLength(extRepr);
send_msg.size = CFDataGetLength(extRepr);
send_msg.flags = 0x1000100u;
send_msg.ndr = NDR_record;
// Make message header
msg = &(send_msg.header);
msg->msgh_bits = 0x80001513u;
msg->msgh_remote_port = configport;
msg->msgh_local_port = mig_get_reply_port();
msg->msgh_id = 20010;
// Request server
msg_return = mach_msg(msg, 3, 0x34u, 0x44u, msg->msgh_local_port, 0, 0);
if(msg_return)
{
if (msg_return - 0x10000002u >= 2 && msg_return != 0x10000010 )
{
mig_dealloc_reply_port(msg->msgh_local_port);
}
else
{
mig_put_reply_port(msg->msgh_local_port);
}
}
else if ( msg->msgh_id != 71 && msg->msgh_id == 20110 && msg->msgh_bits <= -1 )
{
if ((send_msg.flags & 0xFF000000) == 0x1000000)
{
CFDataRef deserializedData = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, send_msg.addr,send_msg.size0, kCFAllocatorNull);
CFPropertyListRef proplist = CFPropertyListCreateWithData(kCFAllocatorDefault, deserializedData, kCFPropertyListImmutable, NULL, NULL);
mig_dealloc_reply_port(msg->msgh_local_port);
mach_port_deallocate(mach_task_self(), bootstrapport);
mach_port_deallocate(mach_task_self(), configport);
mach_msg_destroy(msg);
NSDictionary *property_list = (__bridge NSDictionary*)proplist;
if(proplist)
CFRelease(proplist);
CFRelease(deserializedData);
CFRelease(extRepr);
return property_list;
}
}
mig_dealloc_reply_port(msg->msgh_local_port);
mach_port_deallocate(mach_task_self(), bootstrapport);
mach_port_deallocate(mach_task_self(), configport);
mach_msg_destroy(msg);
CFRelease(extRepr);
return nil;
}
I got a function which should return an intvalue.
- (int)function:(NSString *)input
{
if (input == #"test1")
{
return 0;
}
if (input == #"test2")
{
return 1;
}
if (input == #"test3")
{
return 2;
}
else
{
return 3;
}
}
Here I call the function:
[self function:self.detailItem.type]
The debugger shows input __NSCFString * 0x6b9a0b0 and returns any 29938idontknowvalue.
If I call [self function:#"test1"] everything works fine.
The detailItemis type of TVwhich is a NSManagedObjectwith the attribute type defined as string. Should be a problem with the string-types?
Thank you!
You should compare NSString like this :
if ([input isEqualToString:#"test1"])
{
// Some code here
}
Check that self.detailItem.type is an NSString:
if ([self.detailItem.type isKindOfClass:[NSString class]])
before calling
[self function:self.detailItem.type]
and compare strings like this
[input isEqualToString:#"test1"];
you are currently comparing memory addresses, which in this case will be always different, you should be comparing the strings they contain.