The following code :
-(NSArray *)getContentsWithContextTypes:(NSArray *)contextTypes
contextData:(NSArray *)contextData
{
__block NSString *query = #"SELECT * FROM Texts_original1 WHERE ";
[contextData enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSString *attributeName = [self.contextTypeToDBQueryTexts
objectForKey:contextTypes[idx]];
query = [query stringByAppendingFormat:#"%# = \"%#\"", attributeName, obj];
if(idx != contextData.count - 1)
{
query = [query stringByAppendingString:#" AND "];
}
}];
[self.db open];
FMResultSet *results = [self.db executeQuery:query];
NSMutableArray *array = [NSMutableArray array];
while([results next])
{
Content *content = [[TextualContent alloc] initWithResults:results];
[array addObject:content];
}
[self.db close];
return array;
}
Generates the following error when I run it :
Error calling sqlite3_step (21: out of memory) rs
It happens half way through the loop. There should be 33 results. After 17 I get that error and the loop exits. Any Ideas? Thanks.
It's important to know that you close the FMResultSet object, as it will cause memory problems.
Do it as follows, [resultSet close]
I am not getting into your code logic but, I will make some modifications in database code.
Try the following:
-(NSArray *)getContentsWithContextTypes:(NSArray *)contextTypes
contextData:(NSArray *)contextData
{
__block NSString *query = #"SELECT * FROM Texts_original1 WHERE ";
[contextData enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
NSString *attributeName = [self.contextTypeToDBQueryTexts
objectForKey:contextTypes[idx]];
query = [query stringByAppendingFormat:#"%# = \"%#\"", attributeName, obj];
if(idx != contextData.count - 1)
{
query = [query stringByAppendingString:#" AND "];
}
}];
self.db = [FMDatabase databaseWithPath:[self getDBPath]];
if(![db open])
{
NSLog(#"Could not open DB");
return nil;
}
FMResultSet *results = [self.db executeQuery:query];
NSMutableArray *array = [NSMutableArray array];
while([results next])
{
Content *content = [[TextualContent alloc] initWithResults:results];
[array addObject:content];
}
[results close]; //VERY IMPORTANT!
[self.db close];
return array;
}
Related
I am trying to create a NSMutableArray which will become the dataSource for a UIPickerView, but nothing is getting added to the array, the console just shows (. What am I doing wrong?
NSMutableArray *arr = [[NSMutableArray alloc] init];
PFQuery *rejectedNumber = [PFQuery queryWithClassName:#"Group"];
[rejectedNumber findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!objects) {
// Did not find any UserStats for the current user
NSLog(#"NotFound");
} else {
for (int i=0;i<[objects count];i++)
{
PFObject * obj = [objects objectAtIndex:i];
self.theObject = obj;
NSString *string = obj[#"GroupName"];
[arr addObject:string];
NSLog(#"GOGOGO%#", arr);
}
I am developing a chat app which needs contacts for chatting but when first time it is not showing the contacts again restart the app fetch then it is showing here is my code
-(NSMutableArray *)getAllContacts {
sleep(6);
// The user has previously given access, add the contact
ABRecordRef source = ABAddressBookCopyDefaultSource(addressBookRef);
CFArrayRef allPeople = (ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(addressBookRef, source, kABPersonSortByFirstName));
CFIndex nPeople = ABAddressBookGetPersonCount(addressBookRef);
NSMutableArray* items = [[NSMutableArray alloc] init];
if (!allPeople || !nPeople) {
NSLog(#"people nil");
}
CFStringRef description = CFCopyDescription(allPeople);
NSLog(#"Array %#", description);
CFRelease(description);
for (int i = 0; i < nPeople; i++) {
// #autoreleasepool {
//data model
ContactsData *contacts = [ContactsData new];
ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);
//get First Name
CFStringRef firstName = (CFStringRef)ABRecordCopyValue(person,kABPersonFirstNameProperty);
contacts.firstNames = (__bridge NSString*)firstName;
if (firstName != NULL) {
CFRelease(firstName);
}
//get Last Name
CFStringRef lastName = (CFStringRef)ABRecordCopyValue(person,kABPersonLastNameProperty);
contacts.lastNames = (__bridge NSString*)lastName;
if (lastName != NULL) {
CFRelease(lastName);
}
if (!contacts.firstNames) {
contacts.firstNames = #"";
}
if (!contacts.lastNames) {
contacts.lastNames = #"";
}
contacts.contactId = ABRecordGetRecordID(person);
//append first name and last name
contacts.fullname = [NSString stringWithFormat:#"%# %#", contacts.firstNames, contacts.lastNames];
// get contacts picture, if pic doesn't exists, show standart one
CFDataRef imgData = ABPersonCopyImageData(person);
NSData *imageData = (__bridge NSData *)imgData;
contacts.image = [UIImage imageWithData:imageData];
if (imgData != NULL) {
CFRelease(imgData);
}
if (!contacts.image) {
contacts.image = [UIImage imageNamed:#"avatar.png"];
}
//get Phone Numbers
NSMutableArray *phoneNumbers = [[NSMutableArray alloc] init];
ABMultiValueRef multiPhones = ABRecordCopyValue(person, kABPersonPhoneProperty);
for(CFIndex i=0; i<ABMultiValueGetCount(multiPhones); i++) {
#autoreleasepool {
CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(multiPhones, i);
NSString *phoneNumber = CFBridgingRelease(phoneNumberRef);
phoneNumber = [[phoneNumber componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString:#""];
if (phoneNumber != nil)[phoneNumbers addObject:phoneNumber];
//NSLog(#"All numbers %#", phoneNumbers);
}
}
if (multiPhones != NULL) {
CFRelease(multiPhones);
}
[contacts setNumbers:phoneNumbers];
//get Contact email
NSMutableArray *contactEmails = [NSMutableArray new];
ABMultiValueRef multiEmails = ABRecordCopyValue(person, kABPersonEmailProperty);
for (CFIndex i=0; i<ABMultiValueGetCount(multiEmails); i++) {
#autoreleasepool {
CFStringRef contactEmailRef = ABMultiValueCopyValueAtIndex(multiEmails, i);
NSString *contactEmail = CFBridgingRelease(contactEmailRef);
if (contactEmail != nil)[contactEmails addObject:contactEmail];
// NSLog(#"All emails are:%#", contactEmails);
}
}
if (multiPhones != NULL) {
CFRelease(multiEmails);
}
[contacts setEmails:contactEmails];
[items addObject:contacts];
#ifdef DEBUG
NSLog(#"Person is: %#", contacts.firstNames);
NSLog(#"Phones are: %#", contacts.numbers);
NSLog(#"Email is:%#", contacts.emails);
#endif
}
// } //autoreleasepool
CFRelease(allPeople);
CFRelease(addressBookRef);
CFRelease(source);
return items;
}
now i am getting the contacts and now i am fetching the contacts from
- (NSFetchedResultsController *)fetchedResultsController
{
if (fetchedResultsController == nil)
{
NSManagedObjectContext *moc = [[self appDelegate] managedObjectContext_roster];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"XMPPUserCoreDataStorageObject"
inManagedObjectContext:moc];
NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:#"sectionNum" ascending:YES];
NSSortDescriptor *sd2 = [[NSSortDescriptor alloc] initWithKey:#"displayName" ascending:YES];
NSArray *sortDescriptors = #[sd1, sd2];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:entity];
[fetchRequest setSortDescriptors:sortDescriptors];
[fetchRequest setFetchBatchSize:20];
fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:moc
sectionNameKeyPath:#"sectionNum"
cacheName:nil];
[fetchedResultsController setDelegate:self];
NSError *error = nil;
if (![fetchedResultsController performFetch:&error])
{
DDLogError(#"Error performing fetch: %#", error);
NSLog(#"Error performing fetch");
}
}
return fetchedResultsController;
}
now assigning this fetched controller to array like
self.UserArray=[[[self fetchedResultsController] fetchedObjects] mutableCopy];
but unable to fetch the contacts to tableview where i miss please help me out
FMDatabase *database = [FMDatabase databaseWithPath:databasePath];
[database open];
FMResultSet *results = nil;
results=[database executeQuery:#"SELECT * FROM CLINIQDB"];
while([results next])
{
countryArr=[[NSMutableArray alloc] init];
[countryArr addObject:[results stringForColumn:#"countryNames"]];
}
NSLog(#"The country arr %#",countryArr);
[database close];
Actually I have 10 country names but contryArr showing only last value for example
my countries are {India,Australia,..........,Russia};
countryArr have only Russia in it.
what's wrong with my code.
Initialise your array before of while loop
FMResultSet *results = nil;
results=[database executeQuery:#"SELECT * FROM CLINIQDB"];
countryArr=[[NSMutableArray alloc] init];
while([results next])
{
[countryArr addObject:[results stringForColumn:#"countryNames"]];
}
NSLog(#"The country arr %#",countryArr);
[database close];
Here's my code for returning a unique value for identical keys in a dictionary. Right now, in my log, my "objects array:" is 6 (3 sets of (2 objects with identical keys)), and my "dictionary:" returns values for 1 object from each set (3 unique values). In my 'for' statement:
for (id key in dict)
{
self.titlesArray = [NSMutableArray arrayWithObject:dict];
NSLog(#"titles: %#", self.titlesArray);
self.titlesArray = [[NSMutableArray alloc] initWithObjects:[dict valueForKey:key] ,nil];
NSLog(#"titles: %#", self.titlesArray);
}
The first log prints out the three unique values AND keys. The second prints only a single value for a single key (which is what I want.. but I need all three key values) So my problem now is that I am unable to pull a key for each unique value from the dictionary and add it to my titlesArray.
for (id key in dict)
{
self.titlesArray = [NSMutableArray arrayWithObject:dict];
self.titlesArray = [[NSMutableArray alloc] initWithObjects:[dict valueForKey:key] ,nil];
code isn't quite right.
PFQuery *query = [PFQuery queryWithClassName:#"Images"];
[query whereKey:#"recipientIds" equalTo:[[PFUser currentUser] objectId]];
[query orderByDescending:#"createdAt"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (error) {
NSLog(#"Error: %# %#", error, [error userInfo]);
}
else {
// found messages!
self.objectsArray = objects;
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
for(id obj in self.objectsArray){
PFObject *key = [obj valueForKey:#"titleLabel"];
if(![dict objectForKey:key]){
[dict setValue:key forKey:[obj valueForKey:#"titleLabel"]];
}
}
for (id key in dict) {
self.titlesArray = [NSMutableArray arrayWithObject:dict];
NSLog(#"titles: %#", self.titlesArray);
self.titlesArray = [[NSMutableArray alloc] initWithObjects:[dict valueForKey:key] ,nil];
NSLog(#"titles: %#", self.titlesArray);
}
NSLog(#"dictionary: %#", dict);
NSLog(#"Objects array is %d", [self.objectsArray count]);
[self.pickerView reloadComponent:0];
it looks like there is some type error in line
PFObject *key = [self.objectsArray valueForKey:#"titleLabel"];
it should be
PFObject *key = [obj valueForKey:#"titleLabel"];
It's happening in this line, isn't it:
if(![dict objectForKey:#"titleLabel"]){
[dict setValue:obj forKey:key];
}
}
You are setting "obj" as a value, no problem there, but then you are using "key" which is a PFObject, but NSDictionary requires a NSString for the key.
If PFObject contains a NSString property that you want to use, you can pass that in. For example, if PFObject has an NSString property called "name" you could call this:
if(![dict objectForKey:#"titleLabel"]) {
[dict setValue:obj forKey:key.name];
}
}
The relevant thing to notice is the types of the parameters when NSMutableDictionary defines this method, namely the (NSString*):
- (void)setValue:(id)value forKey:(NSString *)key
How does your PFObject look like. Does it have strings in it?. According to your question you already know that you can't pass a PFObject as key for dictionary. If your object is some what like this
interface PFObject : NSObject
{
NSString *keyString;
......
.Some other variables
}
Then you should be using it like this to set it as key
PFObject *key = [self.objectsArray valueForKey:#"titleLabel"];
if(![dict objectForKey:#"titleLabel"]){
[dict setValue:obj forKey:[key valueForKey#"titleLabel"]];
}
Here is the code I found to work. It takes the array and sorts through the keys to return only unique values for a specific key:
PFQuery *query = [PFQuery queryWithClassName:#"Images"];
[query whereKey:#"recipientIds" equalTo:[[PFUser currentUser] objectId]];
[query orderByDescending:#"createdAt"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (error) {
NSLog(#"Error: %# %#", error, [error userInfo]);
}
else {
// found messages!
self.objectsArray = objects;
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
for(id obj in self.objectsArray){
PFObject *key = [obj valueForKey:#"titleLabel"];
if(![dict objectForKey:key]){
[dict setValue:key forKey:[obj valueForKey:#"titleLabel"]];
}
}
for (id key in dict) {
self.titlesArray = [NSMutableArray arrayWithObject:dict];
[self.titlesArray addObject:dict.allKeys];
self.titlesArray = [self.titlesArray objectAtIndex:1];
}
NSLog(#"titles: %#", self.titlesArray);
[self.pickerView reloadComponent:0];
I create one application and I read many data in table View from JSON and I want parsed this JSON and store in sqlite but I dont know from where should I start?
this is parsed my json code :
#implementation TableViewController
{
NSArray *news;
NSMutableData *data;
NSString *title;
NSMutableArray *all;
}
#synthesize mainTable;
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"News";
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSURL *url = [NSURL URLWithString:#"http://zacandcatie.com/YouTube/json.php"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLConnection *con = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[con start];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
data = [[NSMutableData alloc]init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
[data appendData:theData];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
news = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
for (int i =0; i < [news count]; i++)
{
NSIndexPath *indexPath = [self.mainTable indexPathForSelectedRow];
title =[[news objectAtIndex:indexPath.row+i]objectForKey:#"title"];
if (!all) {
all = [NSMutableArray array];
}
[all addObject:title];
}
NSLog(#"%#",all);
[mainTable reloadData];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *errorView = [[UIAlertView alloc]initWithTitle:#"Error" message:#"The Connection has been LOST" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[errorView show];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
you my json url. I want store "title"&"date_string" value in sqlite.
please guide me!!!
After parsing you data in the form of NSDictionary you can create a query of insert into and fire the query n your data will be save into your database
-(void)InsertRecords:(NSMutableDictionary *)dict
{
sqlite3_stmt *stmt;
sqlite3 *cruddb;
NSMutableString *str = [NSMutableString stringWithFormat:#"Insert into tblName ("];
for (int i = 0; i<[[dict allKeys] count]; i++)
{
[str appendFormat:#"%#,",[[dict allKeys] objectAtIndex:i]];
}
[str appendFormat:#")values ("];
for (int i = 0; i<[[dict allKeys] count]; i++)
{
[str appendFormat:#"%#,",[dict valueForKey:[[dict allKeys] objectAtIndex:i]]];
}
[str appendFormat:#");"];
NSLog(#"qry : %#",str);
const char *sql = [str UTF8String]; ;
if((sqlite3_open([database UTF8String], &cruddb)==SQLITE_OK))
{
if (sqlite3_prepare(database, sql, -1, &stmt, NULL) ==SQLITE_OK)
{
sqlite3_step(stmt);
sqlite3_finalize(stmt);
}
else
{
NSLog(#"Problem with prepare statement: %s", sqlite3_errmsg(database));
}
sqlite3_close(database);
}
else
{
NSLog(#"An error has occured: %s",sqlite3_errmsg(database));
}
}
Try this.
Continuing #Divz Ans...
you will have create the .sqlite file. And there is nothing easier than this.
There are two ways(that i know) to create sqlite file,
1> you can download SQLite Manager add-on in firefox, where you can manipulate data in database graphically.
Or,
2> you can use Terminal with a single line command, sqlite3 dbFileName.sqlite. enter,
where you will get sqlite> now start with further SQL(create/insert/update..) queries.
you can find your sqlite file at MacHD>users>admin(not shared one)>yourFile.sqlite or, finder---go>home>yourFile.sqlite
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
db=[[SKDatabase alloc]initWithFile:#"student.sqlite"];
NSURL *url=[NSURL URLWithString:#"..........Your Url............"];
NSURLRequest *json_request=[[NSURLRequest alloc]initWithURL:url];
NSData *data=[NSURLConnection sendSynchronousRequest:json_request returningResponse:nil error:nil];
NSMutableDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSMutableArray *student_ary=[dic objectForKey:#"students"];
for (NSMutableArray *student_info in student_ary) {
NSMutableDictionary *insert=[[NSMutableDictionary alloc]initWithCapacity:2];
NSMutableDictionary *info=[student_info mutableCopy];
[insert setObject:[info objectForKey:#"name"] forKey:#"name"];
[insert setObject:[info objectForKey:#"city"] forKey:#"city"];
[db insertDictionary:insert forTable:#"student_info"];
}
})
//.m file view....
-(void)viewDidAppear:(BOOL)animated
{
NSString *qry=#"select * from student_info";
ary=[[db lookupAllForSQL:qry] mutableCopy];
[tableView reloadData];
}
You can do some thing like this :
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// tableview cell setup
NSArray* keys = [self.data allKeys];
cell.textLabel.text = [self.data objectForKey:[keys objectAtIndex:indexPath.row]];
return cell;
}
Please refer this links to have data in order in dictionary
NSDictionary with ordered keys