When i NSLog affecteddate values it shows correct but when i store it in var it gives wrong value
SBJsonParser *parser= [[SBJsonParser alloc] init];
NSString *url = [NSString stringWithFormat:#"http://www.krsconnect.no/community/api.html?method=bareListEventsByCategory&appid=620&category-selected=%#&counties-selected=Vest-Agder,Aust-Agder&range=0-10", test];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *object = [parser objectWithString:json_string error:nil];
NSArray *results = [parser objectWithString:json_string error:nil];
appDelegate.books1 = [[NSMutableArray alloc] init];
appDelegate.dates =[[NSMutableArray alloc]init];
appDelegate.books2=[[NSMutableArray alloc]init];
appDelegate.books3=[[NSMutableArray alloc]init];
appDelegate.books4=[[NSMutableArray alloc]init];
appDelegate.books5=[[NSMutableArray alloc]init];
appDelegate.books6=[[NSMutableArray alloc]init];
appDelegate.books7=[[NSMutableArray alloc]init];
appDelegate.books8=[[NSMutableArray alloc]init];
appDelegate.books9=[[NSMutableArray alloc]init];
appDelegate.books10=[[NSMutableArray alloc]init];
NSArray *activitiesArray;
mycount=[results count];
for (int j=0;j<[results count]; j++) {
NSDictionary *dictOne = [results objectAtIndex:j];
NSLog(#"%# - %#", [dictOne objectForKey:#"date"]);
Date *aDate = [[Date alloc] initWithDictionary:[results objectAtIndex:j]];
[appDelegate.dates addObject:aDate];
[aDate release];
activitiesArray = [dictOne objectForKey:#"events"];
for (int i=0; i<[activitiesArray count]; i++) {
int testcount =[activitiesArray count];
NSDictionary *dictTwo = [activitiesArray objectAtIndex:i];
NSDictionary *eventDict=[dictTwo objectForKey:#"event"];
// NSLog(#"%# - %#", [dictOne objectForKey:#"date"]);
// NSLog(#"%# - %#", [dictTwo objectForKey:#"affectedDate"]);
// NSLog(#"%# - %#", [eventDict objectForKey:#"location"]);
NSInteger*date=[dictTwo objectForKey:#"affectedDate"];
NSInteger*affecteddate=[dictTwo objectForKey:#"affectedDate"];
NSLog(#"%# - %#", [dictTwo objectForKey:#"affectedDate"]);
NSString*appId =[eventDict objectForKey:#"appId"];
NSLog(#"%# - %#", [eventDict objectForKey:#"eventId"]);
NSInteger*eventId=[eventDict objectForKey:#"eventId"];
int next=[affecteddate intValue];
int next_int = [eventId intValue];
NSString*location=[eventDict objectForKey:#"location"];
NSString*municipality=[eventDict objectForKey:#"municipality"];
NSString*title=[eventDict objectForKey:#"title"];
Book1 *aBook=[[Book1 alloc] initWithDate:date affecteddate:affecteddate eventId:eventId location:location municipality:municipality title:title];
Book1 class
#interface Book1 : NSObject {
NSInteger*date;
NSInteger*affecteddate;
NSString *title;
NSString *location;
NSString *municipality;
NSInteger eventId;
NSString* event;
}
#property(nonatomic,readwrite) NSInteger eventId;
#property(nonatomic,retain) NSString* event;
#property(nonatomic) NSInteger *date;
#property(nonatomic,readwrite)NSInteger* affecteddate;
#property(nonatomic,retain)NSString *title;
#property(nonatomic,retain) NSString *location;
#property(nonatomic,retain) NSString *municipality;
-(id)initWithDate:(NSInteger *)d affecteddate:(NSInteger *)ad eventId:(NSInteger*)eId location:(NSString *)l municipality:(NSString *)m title:(NSString *)t ;
#end
First you have:
NSInteger*affecteddate=[dictTwo objectForKey:#"affectedDate"];
later
int next=[affecteddate intValue];
intValue is not valid on an integer
You probably want:
NSNumber *date = [dictTwo objectForKey:#"affectedDate"];
NSNumber *affecteddate = [dictTwo objectForKey:#"affectedDate"];
may declare like this in book object to assign this values
NSNumber *affecteddate;
#propert(nonatomic,retain)
Related
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSArray* users = [json objectForKey:#"Users"];
NSEnumerator* enumerator = [users objectEnumerator];
id element;
NSMutableArray *results;
Result *fetchedResults;
while(element = [enumerator nextObject]) {
// fetchedResults = [[Result alloc] init]; // i have tried commenting/uncommenting
fetchedResults.name = (NSString *)[[element objectForKey:#"User"] objectForKey:#"name"];
fetchedResults.email = (NSString *)[[element objectForKey:#"User"] objectForKey:#"name"];
NSLog(#"%#", fetchedResults.name);
[results addObject:fetchedResults];
NSLog(#"%#", (NSString *)[[element objectForKey:#"User"] objectForKey:#"name"]); // this returns valid dump
}
NSLog(#"%d", [results count]); // returns 0
I don't understand wht's wrong here. I have searched through numerous tutorials and resources don't seem to get what's wrong here.
EDIT:
NSLog(#"%#", fetchedResults.name); // dumps null
You forgot to allocate your results array NSMutableArray *results = [[NSMutableArray alloc] init] this should help.
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSArray* users = [json objectForKey:#"Users"];
NSMutableArray *results = [[NSMutableArray alloc] init];
for (id object in users) {
Result *fetchedResults = [[Result alloc] init];
fetchedResults.name = (NSString *)[[element objectForKey:#"User"] objectForKey:#"name"];
fetchedResults.email = (NSString *)[[element objectForKey:#"User"] objectForKey:#"name"];
NSLog(#"%#", fetchedResults.name);
[results addObject:fetchedResults];
}
NSLog(#"%#", (NSString *)[[element objectForKey:#"User"] objectForKey:#"name"]);
}
NSLog(#"%d", [results count]); // returns 0
When my app launches from BACKGROUND , I am running a new thread to get AddresssBook data using notification center. Here is my code which shows how I call the method
-(void)appLaunchedFromBackground:(NSNotification *) notification {
// NSThread *backgroundThread; is my ivar
backgroundThread = [[NSThread alloc]initWithTarget:self selector:#selector(getUpdatedAddressBookData) object:nil];
[backgroundThread start];
}
-(void)getUpdatedAddressBookData {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
AddressBook *addBook = [[AddressBook alloc]init];
[addBook fetchAddressBookDataInBackground];
[addBook release];
[pool drain];
}
Here is my code for fetchAddressBookDataInBackground method
-(void)fetchAddressBookDataInBackground {
if (self.tempArray == nil) {
NSMutableArray *temp = [[NSMutableArray alloc]init];
self.tempArray = temp;
[temp release];
}
ABAddressBookRef addressBook = ABAddressBookCreate();
NSArray *tempPeople = [[NSArray alloc]init];
tempPeople = (NSArray*)ABAddressBookCopyArrayOfAllPeople(addressBook);
APP_DELGATE.people = [NSArray arrayWithArray:tempPeople];
int peoCount = [APP_DELGATE.people count];
for (int i=0; i<peoCount; i++) {
ABRecordRef record = [APP_DELGATE.people objectAtIndex:i];
NSNumber *recordId = [NSNumber numberWithInteger:ABRecordGetRecordID(record)];
// Get fname, lname, company
NSString *fnm = (NSString *)ABRecordCopyValue(record, kABPersonFirstNameProperty) ;
NSString *lnm = (NSString *)ABRecordCopyValue(record, kABPersonLastNameProperty) ;
NSString *comp = (NSString*)ABRecordCopyValue(record,kABPersonOrganizationProperty);
// Get Ph no
ABMultiValueRef phoneNumberProperty = ABRecordCopyValue(record, kABPersonPhoneProperty);
NSArray *tempPhNos = (NSArray*)ABMultiValueCopyArrayOfAllValues(phoneNumberProperty);
NSArray* phoneNumbers = [self getPhoneNoWithoutSymbols:tempPhNos];
NSString *strPhoneNos = [self getStringRepresentaionFromArray:phoneNumbers];
// Get emails
ABMultiValueRef emailProperty = ABRecordCopyValue(record, kABPersonEmailProperty);
NSArray* emails = (NSArray*)ABMultiValueCopyArrayOfAllValues(emailProperty);
NSString *strEmails = [self getStringRepresentaionFromArray:emails];
// Get URL
ABMultiValueRef urlProperty = ABRecordCopyValue(record, kABPersonURLProperty);
NSArray* urls = (NSArray*)ABMultiValueCopyArrayOfAllValues(urlProperty);
NSString *strURLs = [self getStringRepresentaionFromArray:urls];
// Get Address
ABMultiValueRef address=ABRecordCopyValue(record, kABPersonAddressProperty);
CFDictionaryRef dic=nil;
NSMutableArray *addressArray = [[NSMutableArray alloc]init];
for (int index=0; index<ABMultiValueGetCount(address); index++) {
dic=ABMultiValueCopyValueAtIndex(address, index);
NSString* labelName=(NSString*)ABMultiValueCopyLabelAtIndex(address, index);
if (labelName) {
NSString *street =(NSString*) CFDictionaryGetValue(dic, kABPersonAddressStreetKey);
NSString *city= (NSString*)CFDictionaryGetValue(dic, kABPersonAddressCityKey) ;
NSString *state= CFDictionaryGetValue(dic, kABPersonAddressStateKey);
NSString *country=CFDictionaryGetValue(dic, kABPersonAddressCountryKey);
NSString *zipcode=CFDictionaryGetValue(dic, kABPersonAddressZIPKey);
NSString *addressDetails=#"";
if (street) {
addressDetails=[NSString stringWithFormat:#"%# ",street];
}
if (city) {
addressDetails=[NSString stringWithFormat:#"%# %# ",addressDetails,city];
}
if (state) {
addressDetails=[NSString stringWithFormat:#"%# %# ",addressDetails,state];
}
if (country) {
addressDetails=[NSString stringWithFormat:#"%# %# ",addressDetails,country];
}
if (zipcode) {
addressDetails=[NSString stringWithFormat:#"%# %# ",addressDetails,zipcode];
}
[addressArray addObject:addressDetails];
}
[labelName release];
CFRelease(dic);
}
NSString *strAddress = [self getStringRepresentaionFromArray:addressArray];
// Get Notes
NSString *noteString=(NSString *)ABRecordCopyValue(record, kABPersonNoteProperty);
// Get Birthdate
NSDate *birthDate=(NSDate*)ABRecordCopyValue(record, kABPersonBirthdayProperty) ;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MMMM dd yyyy"];
NSString *birthdateString = [formatter stringFromDate:birthDate];
[formatter release];
// Get user image
UIImage *image = nil;
if( ABPersonHasImageData( record ) ) {
NSData *imageData = (NSData*)ABPersonCopyImageData(record);
image = [UIImage imageWithData:imageData];
[imageData release];
}
NSString *fullName = [NSString stringWithFormat:#"%# %#",fnm,lnm];
// Create User object & add it to array
User *user = [[User alloc]initUserWithUniqID:recordId.intValue FirstName:fnm lastName:lnm compositeName:fullName company:comp phoneNumbers:strPhoneNos emails:strEmails urls:strURLs address:strAddress notes:noteString dob:birthdateString userImage:image];
[self.tempArray addObject:user];
CFRelease(phoneNumberProperty);
[tempPhNos release];
CFRelease(emailProperty);
[emails release];
CFRelease(urlProperty);
[urls release];
CFRelease(address);
[addressArray release];
[birthDate release];
[comp release];
[noteString release];
[lnm release];
[fnm release];
[user release];
}
[tempPeople release];
CFRelease(addressBook);
addressBook = nil;
self.tempArray = [NSMutableArray arrayWithArray:[self.tempArray sortedArrayUsingSelector:#selector(compare:)]];
APP_DELGATE.allUsersArray = self.tempArray;
NSDictionary *dic = [NSDictionary dictionaryWithObject:self.tempArray forKey:BATCH_DONE_KEY];
[[NSNotificationCenter defaultCenter] postNotificationName:BACKGROUND_WORK_DONE_NOTIFICATION object:self userInfo:dic];
}
-(NSMutableArray*)getPhoneNoWithoutSymbols:(NSArray*)array {
if (self.phNoArray == nil) {
NSMutableArray *temp = [[NSMutableArray alloc]init];
self.phNoArray = temp;
[temp release];
}
[self.phNoArray removeAllObjects];
for (NSString *str in array) {
[self.phNoArray addObject:[self getPhNo:str]];
}
return self.phNoArray;
}
-(NSString*)getPhNo:(NSString*)str {
NSString *str0 = [str stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *str1 = [str0 stringByReplacingOccurrencesOfString:#"(" withString:#""];
NSString *str2 = [str1 stringByReplacingOccurrencesOfString:#")" withString:#""];
NSString *str3 = [str2 stringByReplacingOccurrencesOfString:#"-" withString:#""];
return str3;
}
-(NSString*)getStringRepresentaionFromArray:(NSArray*)array {
return [array componentsJoinedByString:DELIMITER_SYMBOL];
}
But my app crashes with "Program received EXC_BAD_ACCESS" error at any line where I am using "ABRecordCopyValue" function . What I am missing? I am not getting whats wrong in my code?
I tried setting NSZombieEnabled = YES , but its not showing any message. Just saying "Program received EXC_BAD_ACCESS" at any line using ABRecordCopyValue function & in console I see (gdb) thats it.
Any knid of help is highly appreciated. Thanks.
I need to extract a variable's value from a string, which happens to be a URL. The string/url is loaded as part of a separate php query, not the url in the browser.
The url's will look like:
http://gmail.com?access_token=ab8w4azq2xv3dr4ab37vvzmh&token_type=bearer&expires_in=3600
How can I capture the value of the access_token which in this example is ab8w4azq2xv3dr4ab37vvzmh?
This code should do it:
- (NSString *)extractToken:(NSURL *)URL
{
NSString *urlString = [URL absoluteString];
NSRange start = [urlString rangeOfString:#"access_token="];
if (start.location != NSNotFound)
{
NSString *token = [urlString substringFromIndex:start.location+start.length];
NSRange end = [token rangeOfString:#"&"];
if (end.location != NSNotFound)
{
//trim off other parameters
token = [token substringToIndex:end.location];
}
return token;
}
//not found
return nil;
}
Alternatively, here is a more general solution that will extract all the query parameters into a dictionary:
- (NSDictionary *)URLQueryParameters:(NSURL *)URL
{
NSString *queryString = [URL query];
NSMutableDictionary *result = [NSMutableDictionary dictionary];
NSArray *parameters = [queryString componentsSeparatedByString:#"&"];
for (NSString *parameter in parameters)
{
NSArray *parts = [parameter componentsSeparatedByString:#"="];
NSString *key = [[parts objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
if ([parts count] > 1)
{
id value = [[parts objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[result setObject:value forKey:key];
}
}
return result;
}
Good Category for NSDictionary:
#import "NSDictionary+URL.h"
#implementation NSDictionary (URL)
+ (NSDictionary *)dictionaryWithUrlString:(NSString *)urlString{
NSRange urlRange = [urlString rangeOfString:#"?"];
if(urlRange.length>0){
urlString = [urlString substringFromIndex:urlRange.length+urlRange.location];
}
NSArray *pairsArray = [urlString componentsSeparatedByString:#"&"];
NSMutableDictionary *parametersDictionary = [[NSMutableDictionary alloc] initWithCapacity:[pairsArray count]];
for(NSString *pairString in pairsArray){
NSArray *valuesArray = [pairString componentsSeparatedByString:#"="];
if([valuesArray count]==2){
[parametersDictionary setValue:[valuesArray objectAtIndex:1] forKey:[valuesArray objectAtIndex:0]];
}
}
return [parametersDictionary autorelease];
}
#end
NSMutableDictionary *querycomponent = [[NSMutableDictionary alloc] init];
if (![query isEqualToString:#""]){
NSArray *queryArray = [query componentsSeparatedByString:#"&"];
for (NSString *subquery in queryArray){
NSArray *subqueryArray = [subquery componentsSeparatedByString:#"="];
NSString *key = [subqueryArray objectAtIndex:0];
NSString *val = [subqueryArray objectAtIndex:1];
[querycomponent setObject:val forKey:key];
}
NSLog(#"querycomponent %#",querycomponent);
}
below is the JSON i want to parse it in such a way that for e.g date 1st should all events in that section of table and 2nd date should show all related events in another section
I am parsing using below code but i am not getting required sequence
SBJsonParser *parser= [[SBJsonParser alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.krsconnect.no/community/api.html?method=bareListEventsByCategory&appid=620&category-selected=350&counties-selected=Vest-Agder,Aust-Agder"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *object = [parser objectWithString:json_string error:nil];
NSArray *results = [parser objectWithString:json_string error:nil];
appDelegate.books1 = [[NSMutableArray alloc] init];
appDelegate.dates =[[NSMutableArray alloc]init];
for (int j=0;j<10; j++) {
NSDictionary *dictOne = [results objectAtIndex:j];
NSLog(#"%# - %#", [dictOne objectForKey:#"date"]);
Date *aDate = [[Date alloc] initWithDictionary:[results objectAtIndex:j]];
[appDelegate.dates addObject:aDate];
[aDate release];
}
for (int i=0; i<10; i++) {
NSDictionary *dictOne = [results objectAtIndex:i];
NSArray *activitiesArray = [dictOne objectForKey:#"events"];
NSDictionary *dictTwo = [activitiesArray objectAtIndex:i];
NSDictionary *eventDict=[dictTwo objectForKey:#"event"];
// NSLog(#"%# - %#", [dictOne objectForKey:#"date"]);
// NSLog(#"%# - %#", [dictTwo objectForKey:#"affectedDate"]);
// NSLog(#"%# - %#", [eventDict objectForKey:#"location"]);
NSInteger*date=[dictOne objectForKey:#"date"];
NSInteger*affectedDate=[dictTwo objectForKey:#"affectedDate"];
NSString*appId =[eventDict objectForKey:#"appId"];
NSString*eventId=[eventDict objectForKey:#"eventId"];
NSString*location=[eventDict objectForKey:#"location"];
NSString*municipality=[eventDict objectForKey:#"municipality"];
NSString*title=[eventDict objectForKey:#"title"];
Book1 *aBook=[[Book1 alloc] initWithDate:date affectedDate:affectedDate location:location municipality:municipality title:title];
[appDelegate.books1 addObject:aBook];
int count=[appDelegate.books1 count];
}
the json format is given below
http://www.krsconnect.no/community/api.html?method=bareListEventsByCategory&appid=620&category-selected=350&counties-selected=Vest-Agder,Aust-Agder
You need to aggregate your data in some different way.
Here is how I'd do that:
...
// why do you parse your json string two times?
//NSDictionary *object = [parser objectWithString:json_string error:nil];
NSArray *results = [parser objectWithString:json_string error:nil];
// You have memory leak here. I assume that books1 and dates are both properties with "retain" flag set.
//appDelegate.books1 = [[NSMutableArray alloc] init];
//appDelegate.dates =[[NSMutableArray alloc]init];
NSMutableArray *data = [NSMutableArray array]
self.data = data;
// check that what we've parsed is NSArray
if (results && [results isKindOfClass:[NSArray class]]) {
for (NSDictionary *sectionDict in results) {
if ([sectionDict isKindOfClass:[NSDictionary class]]) {
NSString *sectionTitle = [[sectionDict objectForKey:#"date"] description];
NSArray *events = [sectionDict objectForKey:#"events"];
if (date && events && [events isKindOfClass:[NSArray class]]) {
NSMutableArray *rows = [NSMutableArray arrayWithCapacity:[events count]];
for (NSDictionary *eventDict in events) {
if ([eventDict isKindOfClass:[NSDictionary class]]) {
[rows addObject:#"testRow"];
}
}
[data addObject:[NSDictionary dictionaryWithObjectsAndKeys: sectionTitle, #"section", rows, #"rows", nil]];
}
}
}
}
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tblView {
return [data count];
}
- (NSInteger) tableView:(UITableView *)tblView numberOfRowsInSection:(NSInteger)section {
return [[[data objectAtIndex:section] objectForKey:#"rows"] count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [[data objectAtIndex:section] objectForKey:#"section"];
}
- (UITableViewCell *) tableView:(UITableView *)tblView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellID = #"DefaultCell";
UITableViewCell *cell = (UITableViewCell *)[tblView dequeueReusableCellWithIdentifier:cellID];
if ( cell == nil ) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID] autorelease];
}
cell.textLabel.text = [[[data objectAtIndex:indexPath.section] objectForKey:#"rows"] objectAtIndex:indexPath.row];
return cell;
}
-(void) readRestaurantFromXml {
SGAAppDelegate *app = (SGAAppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *myRequestString = [NSString stringWithFormat:#"%#getXml.aspx",app.SERVER_URL];
NSURL *url = [NSURL URLWithString: myRequestString];
CXMLDocument *rssParser = [[[CXMLDocument alloc] initWithContentsOfURL:url options:0 error:nil] autorelease];
resultNodes = [rssParser nodesForXPath:#"//item" error:nil];
listOfItems = [[NSMutableArray alloc] init];
for (CXMLElement *resultElement in resultNodes) {
NSString *theatre_id = [[resultElement childAtIndex:0] stringValue];
NSString *theatre_name = [[resultElement childAtIndex:1] stringValue];
NSString *restaurant_id = [[resultElement childAtIndex:2] stringValue];
NSString *restaurant_name = [[resultElement childAtIndex:3] stringValue];
NSString *restaurant_desc = [[resultElement childAtIndex:4] stringValue];
NSString *deal_avail = [[resultElement childAtIndex:5] stringValue];
NSString *deal_details = [[resultElement childAtIndex:6] stringValue];
Restaurant *workVal = [[Restaurant alloc] initWithRestTitle:restaurant_name restDesc:restaurant_desc theatreId:theatre_id theatreName:theatre_name restId:restaurant_id restDeals:deal_avail restDealDesc:deal_details];
[listOfItems addObject:workVal];
[workVal release];
}
}
-(void)myTask{
NSLog(#"%d",[listOfItems count]);
}
The NSMutableArray listofItems has 3 values.So how can i extract the array value in another method?
Help me
Fast enumeration is the preferred method.
for (id object in listOfItems) {
//Do something...
}
If you want a single object at an index:
id object = [listOfItems objectAtIndex:someIndex];
If you just want an object (expecting the array to have a single object:
id object = [listOfItems lastObject];
for(int i=0; i < [listOfItems count]; ++i) {
Restaurant* r = [listofItems objectAtIndex:i];
}