How to obtain Home City from Contacts Framework in iOS +9? - objective-c

I am replacing my obsolete ABAdressBook code with the current CNContact framework in Objective C. I could sort out most of it, except for the Home City part, so lets focus on that.
Currently I have this code:
-(NSArray *)getLandAddressesForContactIOS6:(ABRecordRef)recordRef {
ABMultiValueRef addresses = ABRecordCopyValue(recordRef, kABPersonAddressProperty);
NSMutableArray *formattedAddressesResponse = [NSMutableArray array];
for(CFIndex i = 0; i < ABMultiValueGetCount(addresses); i++) {
NSString *label = (__bridge NSString *)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(addresses, i));
NSDictionary *addressComponents = (__bridge NSDictionary*)ABMultiValueCopyValueAtIndex(addresses, i);
NSString *street = [addressComponents objectForKey:(NSString *)kABPersonAddressStreetKey];
NSString *city = [addressComponents objectForKey:(NSString *)kABPersonAddressCityKey];
NSString *formattedAddress = ABCreateStringWithAddressDictionary(addressComponents, YES);
NSMutableDictionary *currentAddressResponse = [NSMutableDictionary dictionaryWithObjectsAndKeys:
label, #"type",
label, #"label",
nil];
if (street != nil) {
[currentAddressResponse setObject:street forKey:#"street"];
}
if (city != nil) {
[currentAddressResponse setObject:city forKey:#"city"];
}
if (formattedAddress != nil) {
[currentAddressResponse setObject:formattedAddress forKey:#"formattedAddress"];
}
[formattedAddressesResponse addObject:currentAddressResponse];
}
return formattedAddressesResponse;
}
That code is deprecated for iOS 9+ so the closest I have got to get the home city with the new Contacts framework is:
-(NSArray *)getLandAddressesForContactIOS10:(CNContact*)recordRef {
NSArray <CNLabeledValue<CNPostalAddress *> *> *addresses = recordRef.postalAddresses;
NSMutableArray *formattedAdressResponse = [NSMutableArray array];
for(CFIndex i = 0; i < addresses.count; i++) {
CNLabeledValue *addressi = [addresses objectAtIndex:i];
//NSString *city = addressi.??????; //Stuck here, don't know what else to do
How can I extract the City name from a CNContact??

-(void )getLandAddressesForContactIOS10:(CNContact*)contact
{
for (CNLabeledValue<CNPostalAddress*>* labeledValue in contact.postalAddresses)
{
NSLog(#"%#",labeledValue.value.city);
NSLog(#"%#",labeledValue.value.street);
NSLog(#"%#",labeledValue.value.state);
NSLog(#"%#",labeledValue.value.postalCode);
NSLog(#"%#",labeledValue.value.ISOCountryCode);
}
}

NSArray *addresses = (NSArray*)[contact.postalAddresses valueForKey:#"value"];
if (!(addresses == nil) && addresses.count > 0)
{
for (CNLabeledValue<CNPostalAddress*>* labeledValue in contact.postalAddresses)
{
NSString *city = labeledValue.value.city;
NSLog(#"City = %#",city);
NSString *street = labeledValue.value.street;
NSLog(#"Street = %#",street);
NSString *state = labeledValue.value.state;
NSLog(#"State = %#",state);
NSString *postalCode = labeledValue.value.postalCode;
NSLog(#"PostalCode = %#",postalCode);
NSString *ISOCountryCode = labeledValue.value.ISOCountryCode;
NSLog(#"ISOCountryCode = %#",ISOCountryCode);
}
}
else
{
NSLog(#"No addresses for name = %#",strname);
}

Related

How can I extract a NSDictionary from an NSDictionary on a lower level

I have an NSDictionary that contains an NSDictionary which also contains NSDictionaries. Now I have code to extract what I need when I only have the website. This is my code.
NSInteger selectedRow = [self.myTableView selectedRow];
NSString *currentName = [self.theFullArray objectAtIndex:selectedRow];
NSMutableArray *theOriginalArray = [self.theDictionary.allKeys mutableCopy];
if ([self.theDictionary.allKeys containsObject:#"#"]) {
[theOriginalArray removeObject:#"#"];
}
NSMutableArray *sortedKeys = [[theOriginalArray sortedArrayUsingDescriptors:#[[NSSortDescriptor sortDescriptorWithKey:#"self" ascending:YES]]] mutableCopy];
if ([self.theDictionary.allKeys containsObject:#"#"]) {
[sortedKeys addObject:#"#"];
}
NSArray *theFullDictObjects = sortedKeys;
NSUInteger theFullDictCount = [theFullDictObjects count];
NSDictionary *currentInfo = nil;
int firstI = 0;
while (firstI < theFullDictCount) {
NSString *currentFullDictObject = [theFullDictObjects objectAtIndex:firstI];
NSDictionary *theSubDict = [self.theDictionary objectForKey:currentFullDictObject];
NSArray *theSubDictObjects = [theSubDict allKeys];
NSUInteger theSubDictCount = [theSubDictObjects count];
int secondI = 0;
while (secondI < theSubDictCount) {
NSString *currentDictObject = [theSubDictObjects objectAtIndex:secondI];
if ([currentName isEqualToString:currentDictObject]) {
NSDictionary *theDict = [theSubDict objectForKey:currentDictObject];
currentInfo = theDict;
break;
}
secondI++;
}
if (currentInfo) {
break;
}
firstI++;
}
NSLog(#"currentInfo: %#", currentInfo);
Now this works but it's kinda slow when you have really big lists of NSDictionaries. Is there another code to do this more effectively or not.
So let's says I have the value "www.adobe.com" then how can I get
<dict>
<key>Name</key>
<string>Adobe</string>
<key>Website</key>
<string>www.adobe.com</string>
<key>Sub Category</key>
<string>Technology</string>
<key>Category</key>
<string>Account</string>
<key>PRLCountry</key>
<string>Belgium</string>
</dict>
If you look at the image, you can see how the dictionary is build.
Thanks in advance.

How to mapping array in YAPdatabase object?

i have test array with objects structure - Group with (NSMutableArray)items, and i save group in YapDatabase
-(void)parseAndSaveJson:(id) json withCompleteBlock:(void(^)())completeBlock{
NSMutableArray *groupsArray = (NSMutableArray *)json;
if (groupsArray != nil) {
YapDatabaseConnection *connectnion = [[DatabaseManager sharedYapDatabase] newConnection];
[connectnion asyncReadWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) {
for (int groupIndex = 0; groupIndex < [groupsArray count]; groupIndex ++) {
LocalGroupsExercise *localGroup = [[LocalGroupsExercise alloc] init];
localGroup.name = groupsArray[groupIndex][LOCAL_GROUPS_NAME];
localGroup.tagColor = groupsArray[groupIndex][LOCAL_GROUPS_TAG_COLOR];
localGroup.idGroup = [groupsArray[groupIndex][LOCAL_GROUPS_ID_GROUP] intValue];
if (groupsArray[groupIndex][LOCAL_GROUPS_EXERCISES] != nil) {
NSMutableArray *exerciseArray = (NSMutableArray *)groupsArray[groupIndex][LOCAL_GROUPS_EXERCISES];
for (int exerciseIndex = 0; exerciseIndex < [exerciseArray count]; exerciseIndex ++) {
LocalExercise *localExercise = [[LocalExercise alloc] init];
localExercise.name = exerciseArray[exerciseIndex][EXERCISE_NAME];
localExercise.exerciseId = [exerciseArray[exerciseIndex][LOCAL_EXERCISE_ID_EXERCISE] intValue];
localExercise.groupId = localGroup.idGroup;
localExercise.type = [exerciseArray[exerciseIndex][EXERCISE_TYPE] intValue];
localExercise.minWeight = [exerciseArray[exerciseIndex][EXERCISE_MIN_WEIGHT] floatValue];
localExercise.maxWeight = [exerciseArray[exerciseIndex][EXERCISE_MAX_WEIGHT] floatValue];
localExercise.minReps = [exerciseArray[exerciseIndex][EXERCISE_MIN_REPS] intValue];
localExercise.maxReps = [exerciseArray[exerciseIndex][EXERCISE_MAX_REPS] intValue];
localExercise.minTimer = [exerciseArray[exerciseIndex][EXERCISE_MIN_TIMER] intValue];
localExercise.maxTimer = [exerciseArray[exerciseIndex][EXERCISE_MAX_TIMER] intValue];
localExercise.timeRelax = [exerciseArray[exerciseIndex][EXERCISE_RELAX_TIME] intValue];
[localGroup.exercises addObject:localExercise];
}
}
[transaction setObject:localGroup forKey:[NSString stringWithFormat:#"%d", localGroup.idGroup] inCollection:LOCAL_GROUPS_CLASS_NAME];
}
YapDatabaseConnection *connectnion = [[DatabaseManager sharedYapDatabase] newConnection];
[connectnion readWithBlock:^(YapDatabaseReadTransaction *transaction) {
LocalGroupsExercise *group = [transaction objectForKey:#"2" inCollection:LOCAL_GROUPS_CLASS_NAME];
NSLog(#"%#", group.name);
NSLog(#"%#", group.tagColor);
NSLog(#"%#", group.exercises);
}];
} completionBlock:^{
completeBlock();
}];
}
}
+ (YapDatabaseView *)setupDatabaseViewForShowGroupsGyms{
YapDatabaseViewGrouping *grouping = [YapDatabaseViewGrouping withObjectBlock:^NSString *(YapDatabaseReadTransaction *transaction, NSString *collection, NSString *key, id object) {
if ([object isKindOfClass:[LocalGroupsExercise class]]) {
LocalGroupsExercise *groupExercise = (LocalGroupsExercise *)object;
return [NSString stringWithFormat:#"%#", groupExercise.name];
}
return nil;
}];
YapDatabaseViewSorting *sorting = [YapDatabaseViewSorting withObjectBlock:^NSComparisonResult(YapDatabaseReadTransaction *transaction, NSString *group, NSString *collection1, NSString *key1, LocalGroupsExercise *obj1, NSString *collection2, NSString *key2, LocalGroupsExercise *obj2) {
return [obj1.name compare:obj2.name options:NSNumericSearch range:NSMakeRange(0, obj1.name.length)];
}];
YapDatabaseView *databaseView = [[YapDatabaseView alloc] initWithGrouping:grouping sorting:sorting versionTag:#"0"];
return databaseView;
}
[[DatabaseManager sharedYapDatabase] registerExtension:self.databaseGroupView withName:LOCAL_GROUPS_CLASS_NAME];
[_connection beginLongLivedReadTransaction];
self.mappingsGroup = [[YapDatabaseViewMappings alloc] initWithGroupFilterBlock:^BOOL(NSString *group, YapDatabaseReadTransaction *transaction) {
return true;
} sortBlock:^NSComparisonResult(NSString *group1, NSString *group2, YapDatabaseReadTransaction *transaction) {
return [group1 compare:group2];
} view:LOCAL_GROUPS_CLASS_NAME];
[_connection readWithBlock:^(YapDatabaseReadTransaction *transaction) {
[self.mappingsGroup updateWithTransaction:transaction];
}];
The problem is that the group be NSMutabblArray and I want to see the objects in the table of the array, but [self.mappingsGroup numberOfItemsInSection:section] return only one items in group
You need to configure YapDatabase to use Mantle. By default, it will use NSCoding. (Which is why you're seeing an error about "encodeWithCoder:", as that method is part of NSCoding.)
Take a look at YapDatabase's wiki article entitled "Storing Objects", which talks about how it uses the serializer/deserializer blocks: https://github.com/yaptv/YapDatabase/wiki/Storing-Objects
Basically, when you alloc/init your YapDatabase instance, you'll want to pass a serializer & deserializer block that uses Mantle to perform the serialization/deserialization.
Also, see the various init methods that are available for YapDatabase: https://github.com/yaptv/YapDatabase/blob/master/YapDatabase/YapDatabase.h

Searching array kept in NSDictionary

I am having a requirement in which I have 5 keys stored in a NSDictionary corresponding to which I have stored 5 values from different arrays. My data structure looks like:
Dictionary is {
1 = (
{
SubRegionName = "abc";
WalkId = 123;
WalkName = xyz;
},
{
},....
2 = (
{
SubRegionName = "abc";
WalkId = 123;
WalkName = xyz;
},
{
},....
3 = (
{
SubRegionName = "abc;
WalkId = 123;
WalkName = xyz;
},
{
},....
4 = (
{
SubRegionName = "abc";
WalkId = 123;
WalkName = xyz;
},
{
},....
5 = (
{
SubRegionName = "abc";
WalkId = 123;
WalkName = xyz;
},
{
},
)
The above data I am getting from sqlite according to some Id say tempId(1,2,3,4,5) and I want to use them separately. As I have to display the walkName as cell.textlabel.text and SubregionName as cell.detailtext.text in tableview.
I am not getting how to access this data from the dictionary. Can anyone please suggest me right way to do it.
My code is:
// For Database queries (To get data from database) ***********
-(void)getMainRegions
{
sqlite3 *walkNameDB;
if (sqlite3_open([[self databasePath] UTF8String], &walkNameDB) != SQLITE_OK) {
sqlite3_close(walkNameDB);
NSAssert(0, #"Failed to open Walk name database");
}
NSString *regionQuery = #"SELECT Rid,RName from MainRegions";
sqlite3_stmt *teststatement = nil;
// NSLog(#"%d",sqlite3_prepare_v2(walkNameDB,[regionQuery UTF8String], -1, &teststatement, nil));
if (sqlite3_prepare_v2(walkNameDB,[regionQuery UTF8String], -1, &teststatement, nil) == SQLITE_OK)
{
RNameArray = [[NSMutableArray alloc] init];
RIdArray = [[NSMutableArray alloc] init];
while( sqlite3_step(teststatement) == SQLITE_ROW )
{
NSNumber *RId;
int temp1 = (int)sqlite3_column_int(teststatement, 0);
RId = [[NSNumber alloc] initWithInt:temp1];
char *RNameCharacter;
RNameCharacter = (char *) sqlite3_column_text(teststatement, 1);
NSString *RNameString = [[NSString alloc] initWithUTF8String:RNameCharacter];
[RNameArray addObject:RNameString];
[RIdArray addObject:RId];
}
}
[self getWalks];
}
-(void)getWalks
{
sqlite3 *walkNameDB;
if (sqlite3_open([[self databasePath] UTF8String], &walkNameDB) != SQLITE_OK) {
sqlite3_close(walkNameDB);
NSAssert(0, #"Failed to open Walk name database");
}
RegionWalksDictionary = [[NSMutableDictionary alloc] init];
for(regionId in RIdArray)
{
regionWalkArray = [[NSMutableArray alloc] init];
NSString *walkQuery = [[NSString alloc] initWithFormat:#"SELECT Wid,WName,SName from Walks,SubRegions WHERE Walks.Sid=SubRegions.Sid AND Rid = %d",[regionId integerValue] ];
sqlite3_stmt *walkstatement = nil;
// NSLog(#"%d",sqlite3_prepare_v2(walkNameDB,[walkQuery UTF8String], -1, &walkstatement, nil));
if (sqlite3_prepare_v2(walkNameDB,[walkQuery UTF8String], -1, &walkstatement, nil) == SQLITE_OK)
{
while( sqlite3_step(walkstatement) == SQLITE_ROW )
{
NSNumber *WId;
int temp1 = (int)sqlite3_column_int(walkstatement, 0);
WId = [[NSNumber alloc] initWithInt:temp1];
char *WNameCharacter;
WNameCharacter = (char *) sqlite3_column_text(walkstatement, 1);
NSString *WNameString = [[NSString alloc] initWithUTF8String:WNameCharacter];
char *SNameCharacter;
SNameCharacter = (char *) sqlite3_column_text(walkstatement, 2);
NSString *SNameString = [[NSString alloc] initWithUTF8String:SNameCharacter];
NSMutableDictionary *tempWalk = [[NSMutableDictionary alloc] init];
[tempWalk setObject:WId forKey:#"WalkId"];
[tempWalk setObject:WNameString forKey:#"WalkName"];
[tempWalk setObject:SNameString forKey:#"SubRegionName"];
[regionWalkArray addObject:tempWalk];
}
}
[RegionWalksDictionary setObject:regionWalkArray forKey:regionId];
// NSLog(#"arr%#",RegionWalksDictionary);
}
}
//*** Methods to get data from database ends here **************
Try this way...
for(id dict in RegionWalksDictionary){
NSLog(#"WalkId: %#",[[[RegionWalksDictionary objectForKey:dict]objectAtIndex:0]objectForKey:#"WalkId"] );
NSLog(#"WalkName: %#",[[[RegionWalksDictionary objectForKey:dict]objectAtIndex:0]objectForKey:#"WalkName"] );
NSLog(#"SubRegionName: %#",[[[RegionWalksDictionary objectForKey:dict]objectAtIndex:0]objectForKey:#"SubRegionName"] );
NSLog(#"----");
}
I have used as following (comment if this is not the structure or your data)
NSMutableDictionary *RegionWalksDictionary=[NSMutableDictionary new];
NSMutableArray *regionWalkArray=[NSMutableArray new];
NSMutableDictionary *tempWalk=[NSMutableDictionary new];
[tempWalk setObject:#"wk1" forKey:#"WalkId"];
[tempWalk setObject:#"wkName1" forKey:#"WalkName"];
[tempWalk setObject:#"srName1" forKey:#"SubRegionName"];
[regionWalkArray addObject:tempWalk];
[RegionWalksDictionary setObject:regionWalkArray forKey:#"1"];
[RegionWalksDictionary setObject:regionWalkArray forKey:#"2"];
[RegionWalksDictionary setObject:regionWalkArray forKey:#"3"];
NSLog(#"tempWalkd dict is %#",RegionWalksDictionary);
try this
NSString * walkName = [[parentDic objectForKey:[NSString stringWithFormat:#"%d",indexPath.row]] objectForKey:#"WalkName"];
NSString * SubregionName = [[parentDic objectForKey:[NSString stringWithFormat:#"%d",indexPath.row]] objectForKey:#"SubRegionName"];
It seems you have an NSDictionary with your 5 keys, and inside that you have an NSArray with a single element that is a NSDictionary. Although I might be wrong, try this:
NSDictionary *dictionaryForKey1 = [[myDictionary objectForKey:#"1"] objectAtIndex:0];
You can then use this:
NSString *walkName = [dictionaryForKey1 objectForKey:#"WalkName"];
AH! now I see it -- there are 5 arrays of length 1
NSArray *array1 = dict[#"1];
NSDictionary *details = array1[0];
//print each var
id WalkName = details[#"WalkName"];

Split NSString with multiple delimiters?

For text bozo__foo!!bar.baz, how to split an NSString containing this into (bozo, foo, bar, baz)?
That is, separe it in components with strings (delimiters) __, !! and ..
You can split the strings using NSCharacterSet. Try this
NSString *test=#"bozo__foo!!bar.baz";
NSString *sep = #"_!.";
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:sep];
NSArray *temp=[test componentsSeparatedByCharactersInSet:set];
NSLog(#"temp=%#",temp);
I'm aware that this question has already been answered but this is a way to separate strings using multiple strings. This is a category to NSString.
- (NSArray<NSString *> *)componentsSeparatedByStrings:(NSArray<NSString *> *)separators
{
NSMutableArray<NSString *> *components = [[NSMutableArray alloc] init];
unichar buffer[self.length + 1];
NSInteger currentOrigin = 0;
NSInteger currentLength = 0;
[self getCharacters:buffer];
for(NSInteger i = 0; i < self.length; i++)
{
unichar currentChar = buffer[i];
currentLength++;
for(NSInteger n = 0; n < separators.count; n++)
{
NSString *currentDivider = [separators objectAtIndex:n];
if(currentDivider.length == 0)
{
return #[self];
}
else if(currentDivider.length > 1)
{
BOOL goodMatch = NO;
for(NSInteger x = 0; x < currentDivider.length; x++)
{
unichar charInDivider = [currentDivider characterAtIndex:x];
if(charInDivider == currentChar)
{
goodMatch = YES;
}
else
{
goodMatch = NO;
break;
}
if(goodMatch == YES && ((x + 1) != currentDivider.length))
{
i++;
currentLength++;
currentChar = buffer[i];
}
}
if(goodMatch == YES)
{
NSRange newComponentRange = NSMakeRange(currentOrigin, (currentLength - currentDivider.length));
NSString *newComponent = [self substringWithRange:newComponentRange];
currentOrigin = (i + 1);
currentLength = 0;
[components addObject:newComponent];
NSLog(#"%#", components);
}
}
else // If current divider is only one character long.
{
if([currentDivider characterAtIndex:0] == currentChar)
{
NSRange newComponentRange = NSMakeRange(currentOrigin, (currentLength - 1));
NSString *newComponent = [self substringWithRange:newComponentRange];
currentOrigin = (i + 1);
currentLength = 0;
[components addObject:newComponent];
break;
}
}
}
// Handle the end of the string.
if((i + 1) == self.length)
{
NSRange newComponentRange = NSMakeRange(currentOrigin, currentLength);
NSString *newComponent = [self substringWithRange:newComponentRange];
currentOrigin = 0;
currentLength = 0;
[components addObject:newComponent];
}
}
return components;
}
Example: "ABCD__EFGHI__JKLMNOP-QRST.UV_WXYZ"
NSLog(#"%#", [test componentsSeparatedByStrings:#[#"__", #"-", #"."]]);
Log Result: "(ABCD, EFGHI, JKLMNOP, QRST, "UV_WXYZ")"
NSString *text = #"bozo__foo!!bar.baz";
NSArray *split1 = [text componentsSeparatedByString:#"__"];
NSArray *split2 = [[split1 lastObject] componentsSeparatedByString:#"!!"];
NSArray *split3 = [[split2 lastObject] componentsSeparatedByString:#"."];
NSLog(#"%#, %#, %#, %#", split1[0], split2[0], split3[0], split3[1]);
More functional solution is to apply -componentsSeparatedByString: recursively, for each component, which was derived during previous separator application:
NSString Category
- (NSMutableArray<NSString *> *)gvr_componentsSeparatedByStrings:(NSArray<NSString *> *)separators {
if (separators.count == 0) {
return [NSMutableArray arrayWithObject:self];
}
NSString *separator = [separators firstObject];
NSArray *reducedSeparators = [separators gvr_arrayByRemovingFirstObject];
NSArray *components = [self componentsSeparatedByString:separator];
NSMutableArray *result = [NSMutableArray new];
for (NSString *component in components) {
NSMutableArray *subResult = [component gvr_componentsSeparatedByStrings:reducedSeparators];
[result addObjectsFromArray:subResult];
}
return result;
}
NSArray Category
- (NSArray *)gvr_arrayByRemovingFirstObject {
NSMutableArray *result = [NSMutableArray new];
for (NSInteger i = 1; i < self.count; i++) {
[result addObject:self[i]];
}
return [result copy];
}
I solved it for my project by looking for the longest separator, replacing the others with this one, then do the separation on the only one left.
Try this:
NSString *test = #"bozo__foo!!bar.baz";
test = [test stringByReplacingOccurrencesOfString:#"!!" withString:#"__"];
test = [test stringByReplacingOccurrencesOfString:#"." withString:#"__"];
NSArray<NSString *> *parts = [test componentsSeparatedByString:#"__"];

Create Generic Function For Database Selects

I'm developing an iPhone app. I've got a function that reads data from a sqlite database and puts the results into an array. Everything works fine. Here is part of the function that fills the array:
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
NSString *aVar1 = [NSString stringWithUTF8String(char*)sqlite3_column_text(compiledStatement, 0)];
NSString *aVar2 = [NSString stringWithUTF8String(char*)sqlite3_column_text(compiledStatement, 1)];
NSArray *anArray = [NSArray arrayWithObjects:aVar1,aVar2,nil];
[returnArray addObject:anArray]
[anArray release];
}
//return the array
I want to make this function more generic so that it takes a sql statement string as a parameter, and returns a mutablearray of arrays, no matter how many columns are in the result set.
Is there a way to do this? The solution doesn't have to include arrays -- could be any collection object. I'm just looking for a way to make the function re-usable for other queries to the same database.
Couldn't you just do something like:
int numCols = sqlite3_column_count(compiledStatement);
NSMutableArray *result = [NSMutableArray array];
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
NSMutableArray *array = [NSMutableArray array];
for (int i = 0; i < numCols; i++) {
[array addObject:
[NSString stringWithUTF8String:
(char *)sqlite3_column_text(compiledStatement, i)]];
}
[result addObject:array];
}
+(NSArray *)executeQueryAndReturnArray:(NSString *)query {
sqlite3_stmt *statement = nil;
const char *sql = [query UTF8String];
if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) != SQLITE_OK) {
NSLog(#"[SQLITE] Error when preparing query!");
} else {
NSMutableArray *result = [NSMutableArray array];
while (sqlite3_step(statement) == SQLITE_ROW) {
NSMutableArray *row = [NSMutableArray array];
for (int i = 0; i < sqlite3_column_count(statement); i++) {
int colType = sqlite3_column_type(statement, i);
id value;
if (colType == SQLITE_TEXT) {`enter code here`
const unsigned char *col = sqlite3_column_text(statement, i);
value = [NSString stringWithFormat:#"%s", col];
} else if (colType == SQLITE_INTEGER) {
int col = sqlite3_column_int(statement, i);
value = [NSNumber numberWithInt:col];
} else if (colType == SQLITE_FLOAT) {
double col = sqlite3_column_double(statement, i);
value = [NSNumber numberWithDouble:col];
} else if (colType == SQLITE_NULL) {
value = [NSNull null];
} else {
NSLog(#"[SQLITE] UNKNOWN DATATYPE");
}
[row addObject:value];
}
[result addObject:row];
}
return result;
}
return nil;
}