Im setting up a map, with some MKAnnotation. When i add them to the map, I receive this message:
An instance 0xbe62850 of class ENTAnottation was deallocated while key value observers were still registered with it. Observation info was leaked, and may even become mistakenly attached to some other object. Set a breakpoint on NSKVODeallocateBreak to stop here in the debugger. Here's the current observation info:
(
Context: 0x0, Property: 0xbe66b30>
If i am not mistaken, that means that an object has been deallocated while their observer are still alive. How can I know wich are the observers? and, even if I find them... isn't explicit deallocation forbidden with ARC? if thats true, i could not deallocate them... so... what could i do?
Thank you.
-------EDIT------
By request, I post my code. I make a call to a web that returns me a JSON with the values that I need to set my Annotations:
- (void)requestFinished:(ASIHTTPRequest *)request
{
responseString = [request responseString];
id jsonObject = [responseString objectFromJSONString];
NSLog(#"From the JSON: %#", responseString);
NSMutableArray *lat = [jsonObject valueForKeyPath:#"latitud"];
NSMutableArray *lon = [jsonObject valueForKeyPath:#"longitud"];
NSMutableArray *azafatas = [jsonObject valueForKeyPath:#"azafata"];
NSMutableArray *usernames = [jsonObject valueForKeyPath:#"username"];
NSMutableArray *mapazafatas=[[NSMutableArray alloc]init];
for(int i=0;i<[lat count]; i++)
{
ENTAnottation *azafata=[[ENTAnottation alloc]init];
double latidouble=[[lat objectAtIndex:i]doubleValue];
double longdouble=[[lon objectAtIndex:i]doubleValue];
CLLocationDegrees lati=latidouble;
CLLocationDegrees longi=longdouble;
CLLocationCoordinate2D coords=CLLocationCoordinate2DMake(lati, longi);
NSString *nombre=[azafatas objectAtIndex:i];
NSString *email=[usernames objectAtIndex:i];
azafata.coordinate=coords;
azafata.title=nombre;
azafata.username=email;
[mapazafatas addObject:azafata];
//[mapa addAnnotation:azafata];
}
for (int i=0;i<[mapazafatas count];i++)
{
[mapa addAnnotation:[mapazafatas objectAtIndex:i]];
}
}
After that, the app crashes, despite it goes through my code without any problem.
Solved. Obviously, if you pass an impossible pair of coordinates it throws to your face that very clear, and impossible to confuse anybody, error message. Pity me...
Related
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[jsonArray removeAllObjects];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
responseData = nil;
NSMutableArray *sdf = [(NSDictionary*)[responseString JSONValue] objectForKey:#"DataTable"];
NSMutableArray * myArray = [[NSMutableArray alloc] init];
NSMutableDictionary * myDict = [[NSMutableDictionary alloc] init];
if (([(NSString*)sdf isEqual: [NSNull null]])) {
// Showing AlertView Here
}else {
for (int i=0; i<[sdf count]; i++) {
myDict=[sdf objectAtIndex:i];
[myArray addObject:[myDict objectForKey:#"RxnCustomerProfile"]];
}
jsonArray=[myArray mutableCopy];
NSMutableDictionary *dict=[jsonArray objectAtIndex:0];
if ([dict count]>1) {
// Showing AlertView Here
}
}
}
Hi Everyone, I have an issue regarding the -[__NSArrayM objectForKey:]: .
Tried to solve but did not get the better solution for it. Please help me to
find the solution. Thanks In Advance
Below is the issues
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0x19731d40'
This is a debugging problem and nobody can really solve it for you as you are using non-local variables whose definition and values are unknown, don't mention that you are using SBJSON (I guess), etc. But let's see if we can give you some pointers. Your error:
[__NSArrayM objectForKey:]: unrecognized selector sent to instance
That tells you that you sent a dictionary method (objectForKey) to an array (__NSArrayM). So somewhere you have an array when you think you have a dictionary.
Now you declare and allocate a dictionary:
NSMutableDictionary * myDict = [[NSMutableDictionary alloc] init];
but then assign to it:
myDict=[sdf objectAtIndex:i];
So this discards the dictionary you allocated and instead assigns whatever is at index i in the array sdf. How do you know, as opposed to think, that the element of the array is a dictionary? You don't test to check...
So where did sdf come from? This line:
NSMutableArray *sdf = [(NSDictionary*)[responseString JSONValue] objectForKey:#"DataTable"];
So that calls JSONValue on some unknown string, assumes the result is a dictionary (could it be an array? or a failure?), looks up a key (did your error come from this line?), and assumes the result is an array.
So what you need to do is go and test all those assumptions, and somewhere you'll find an array where you think you have a dictionary.
Happy hunting!
YOU FETCH THE VALUE IN ARRAY FORMAT AND YOU INTEGRATE METHOD IN DICTIONARY.
You do not need to iterate keys and values of dict can directly pass values to array inside else part like:
myArray = [sdf objectForKey:#"RxnCustomerProfile"];
Key RxnCustomerProfile itself containing array not dictionary.
Change your if else part use below code:
if (([(NSString*)sdf isEqual: [NSNull null]])) {
// Showing AlertView Here
}else {
myArray = [sdf objectForKey:#"RxnCustomerProfile"];
}
NSMutableArray *sdf = [(NSDictionary*)[responseString JSONValue] objectForKey:#"DataTable"];
Check Sdf
if([sdf isKindOfClass:[NSDictionary class]])
{
NSLog(#"Dictionary");
}
else if([sdf isKindOfClass:[NSArray class]])
{
NSLog(#"NSArray");
}
else if([sdf isKindOfClass:[NSMutableArray class]])
{
NSLog(#"NSMutableArray");
}
First of all it seems like your json is not actually correctly formatted. Without knowing what responseData looks like it's difficult to say exactly what is wrong. But in your code there are a few areas where it can be improved.
First of all you don't need to use [responseString JSONValue]. You can short circuit it entirely with
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
NSArray *sdf = responseDictionary[#"DataTable"];
Now, the rest all depends on the data in responseData.
But you can make your code a little bit cleaner with (if I understand what you're trying to achieve correctly:
NSMutableArray *myArray = [NSMutableArray array];
if ([sdf isEqual:[NSNull null]]) {
// Showing AlertView here
} else {
for (NSDictionary *myDict in sdf) {
[myArray addObject:dict[#"RxnCustomerProfile"]];
}
}
// No idea what you're trying to achieve here, but here goes:
jsonArray = [myArray mutableCopy];
NSDictionary *dict = jsonArray.first;
if (dict.count > 1) {
// Showing AlertView here
}
Some things to note. You make very liberal use of NSMutableArray and NSMutableDictionary for no apparent reason. Only use mutable if you're actually changing the array or dictionary.
- (void)viewDidLoad
{
binding.logXMLInOut = YES; // to get logging to the console.
StationDetailsJsonSvc_getAvailableStations *request = [[StationDetailsJsonSvc_getAvailableStations new] autorelease];
request.userName=#"twinkle";
request.password=#"twinkle";
StationDetailsJsonSoap11BindingResponse *resp = [binding getAvailableStationsUsingParameters:request];
for (id mine in resp.bodyParts)
{
if ([mine isKindOfClass:[StationDetailsJsonSvc_getAvailableStationsResponse class]])
{
resultsring = [mine return_];
NSLog(#"list string is%#",resultsring);
}
}
#pragma mark parsing
SBJsonParser *parserq = [[SBJsonParser alloc] init];
//if successful, i can have a look inside parsedJSON - its worked as an NSdictionary and NSArray
results= [parserq objectWithString:resultsring error:nil];
NSLog(#"print %#",results);
for (status in results)
{
NSLog(#"%# ",[status objectForKey:#"1" ]);
events=[status objectForKey:#"1"];
NSLog(#"get%#",events);
NSLog(#"events%#",events);
}
events=[status objectForKey:#"1"];
NSLog(#"post%#",events);
self.navigationController.navigationBarHidden=YES;
[whethertableview reloadData];
[super viewDidLoad];
}
this is my code am not getting tableview contents if i run my app crashes getting [NSCFString count]:unrecognized selector sent to instance
You should not get count on NSString but on arrays
you should call [yourString length] to check if the string has something.
You are trying to get the count of a string , which is crashing the App
There are various improvements you could make with this code, but I think I see the problem:
As you are not using ARC, you need to retain what you take out of the parser:
So instead of:
events=[status objectForKey:#"1"]
You need to do:
events= [[status objectForKey:#"1"] retain];
Your crash is caused by accessing a variable that has already been released. More than likely it is the events variable.
...and to add to this. events is probably an NSArray which 'count' is being called on. And [status objectForKey:#"1"] is returning a string... there are many possibilities which i'm speculating about. If events is an NSArray, this isn't the way to add objects to the array.. you repeatedly call events=[status objectForKey:#"1"]; in a loop too.
I just used this answer to set up a data request from Yahoo Finance. If you take a look at the post, you'll see it returns a dictionary of data (in this case, bids) and keys (symbols). Just to test it, I used this code, but it continues to crash:
NSArray *tickerArray = [[NSArray alloc] initWithObjects:#"AAPL", nil];
NSDictionary *quotes = [self fetchQuotesFor:tickerArray];
NSLog(#"%#",[quotes valueForKey:#"AAPL"]);
Can you point out what I'm doing wrong? I need to get a string containing the data for the symbols I ask for.
PLEASE NOTE:My code is using the code that this post was based on, i.e. this.
The code you liked to is making the wrong assumption about the shape of the JSON data coming back from the API and you're getting a standard KVC error. reason: '[<__NSCFString 0x7685930> valueForUndefinedKey:]: this class is not key value coding-compliant for the key BidRealtime.'
With some debugging I got it working...
Based on your input array and by slightly modifying the function linked too, you need to access the quote like so:
#define QUOTE_QUERY_PREFIX #"http://query.yahooapis.com/v1/public/yql?q=select%20symbol%2C%20BidRealtime%20from%20yahoo.finance.quotes%20where%20symbol%20in%20("
#define QUOTE_QUERY_SUFFIX #")&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback="
+ (NSDictionary *)fetchQuotesFor:(NSArray *)tickers {
NSMutableDictionary *quotes;
if (tickers && [tickers count] > 0) {
NSMutableString *query = [[NSMutableString alloc] init];
[query appendString:QUOTE_QUERY_PREFIX];
for (int i = 0; i < [tickers count]; i++) {
NSString *ticker = [tickers objectAtIndex:i];
[query appendFormat:#"%%22%#%%22", ticker];
if (i != [tickers count] - 1) [query appendString:#"%2C"];
}
[query appendString:QUOTE_QUERY_SUFFIX];
NSData *jsonData = [[NSString stringWithContentsOfURL:[NSURL URLWithString:query] encoding:NSUTF8StringEncoding error:nil] dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *results = jsonData ? [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil] : nil;
NSDictionary *quoteEntry = [results valueForKeyPath:#"query.results.quote"];
return quoteEntry;
}
return quotes;
}
You'll notice the difference between the code I've posted here and the function you linked too is the final parsing of quoteEntry. I worked out what it was doing with some breakpoints, specifically on all exceptions that lead me to the exact line.
All you have to do is initialize the NSMutableDictionary!
NSMutableDictionary *quotes = [[NSMutableDictionary alloc] init];
BTW the guy above is totally NOT making use of the quotes dict. straight up returning the quoteEntry. Skipping one step. :)
I'm making an app that displays the user on the map along with multiple restaurant listings. When the user taps a pin, it stores the coordinates from the annotation and compares them against the users to ensure they are different. Once it is determined that they are different, it sends the coordinates of the business along with the coordinates of the user to Google to request directions. The code is working fine, but in order for it to do so I had to declare a few variables in ways that cause memory leaks. I'm hoping to clean the code up and learn where I erred and the proper way this should be handled.
So below is my code for getting the coordinates from the annotation that was tapped. If I attempt to initialize selectedAnnotation and allocate it's memory in say viewDidLoad by putting selectedAnnotation = [[MapLocation alloc] init]; Then it still shows up as a memory leak. And for reference, selectedAnnotation is a MapLocation(that conforms to MKAnnotation) variable, and as a property I have it (nonatomic, retain) and #synthesize(d).
I thought as long as I allocated it in memory, so long as I set its value to nil in viewDidUnload and released it in dealloc, that there should be no memory issues. What am I missing? Below is a screen shot of my memory leaks when I allocate the memory for selectedAnnotation in viewDidLoad along with the code provided below. If I have already allocated the memory, and check that the variable exists, why would it allocate the memory for the variable again? This happens for any restaurant pin I click on, but obviously not on the user's pin, because I have the code to release it in that case.
-(void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
//NSLog(#"Selected annotation view");
// if we don't have the place holder already allocated
// lazy load the MapLocation placeholder variable
if(!selectedAnnotation)
{
selectedAnnotation = [[MapLocation alloc] init];
}
// save the annotation clicked
selectedAnnotation = view.annotation;
// if the annotation selected was is the same as the user's location
if((selectedAnnotation.coordinate.latitude == savedUserLocation.coordinate.latitude) && (selectedAnnotation.coordinate.longitude == savedUserLocation.coordinate.longitude))
{
// set it to nil and release it
selectedAnnotation = nil;
[selectedAnnotation release];
}
}
I'm having similar trouble with memory issues with the method below. I'm bringing in the JSON data from Google, to extract the address and coordinates of the user's location to display in the AnnotationView. I created all the necessary Arrays and Dictionaries to access the information, but once I allocate the memory for them and assign their values to savedUserLocation, if I try releasing say the NSDictionary variable userLocation, even as the last line of code in this method, the app crashes due to "[CFDictionary release]: message sent to deallocated instance 0x83ccb60". I'm pretty sure it's because I'm setting the values in savedUserLocation via pointer, and once the memory is released that information no longer exists, so what would be the proper way to allocate/release the memory to where I can access the information, without causing memory leaks? I've also tried using autorelease, but the same issues persist.
Here is the code that places the user pin.
- (void)fetchedData:(NSData *)responseData
{
//parse out the json data
NSError *error;
NSDictionary *json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSArray *results = [json objectForKey:#"results"]; //2
NSUInteger counter = [results count];
NSDictionary *userLocation = [[NSDictionary alloc] init];
//NSString *address = [[NSString alloc] init];
for(NSUInteger i=0; i < counter; i++)
{
userLocation = [results objectAtIndex:i];
// 2) Get the funded amount and loan amount
NSString *address = [[NSString alloc] initWithString:[userLocation objectForKey:#"formatted_address"]];
NSArray *types = [userLocation objectForKey:#"types"];
NSDictionary *geometry = [userLocation objectForKey:#"geometry"];
NSDictionary *location = [geometry objectForKey:#"location"];
float lat = [[location objectForKey:#"lat"] floatValue];
float lon = [[location objectForKey:#"lng"] floatValue];
CLLocationCoordinate2D newCoordinates;
newCoordinates.latitude = lat;
newCoordinates.longitude = lon;
// count how many types there are
NSUInteger numberOfTypes = [types count];
NSString *type = [[NSString alloc] init];
for(NSUInteger j=0; j < numberOfTypes; j++)
{
type = [types objectAtIndex:j];
if([type rangeOfString:#"street_address" options:NSCaseInsensitiveSearch].location != NSNotFound)
{
NSLog(#"%#", address);
if(!savedUserLocation)
{
savedUserLocation = [[MapLocation alloc] init];
}
[savedUserLocation setTitle:#"You are here!"];
[savedUserLocation setSubtitle:address];
[savedUserLocation setCoordinate:newCoordinates];
}
}
}
// determine which location is closest to the user by calling this function
MapLocation *closestLocation = [self determineClosestLocationToUser:allLocations locationOfUser:savedUserLocation];
// send in the user location and the closest store to them to determine appropriate zoom level and
// to center the map between the two
[self determineMapCenterAndZoomLevelFromUser:savedUserLocation andClosestLocation:closestLocation];
if(!pinDropped)
{
// add the annotation to the map and then release it
[mapView addAnnotation:savedUserLocation];
pinDropped = true;
}
}
Thanks for any and all help/suggestions/advice. I'd really like to understand the nuts and bolts of what I'm doing wrong, as I thought I had a pretty decent grasp on it.
In didSelectAnnotationView, you have this code:
selectedAnnotation = nil;
[selectedAnnotation release];
This causes a memory leak because you are setting selectedAnnotation to nil and then calling release on it.
The call to release does nothing because selectedAnnotation is nil at that point and a call to nil does nothing. This means the memory that had been allocated is never released but since the pointer variable has been set to nil, when didSelectAnnotationView is called again, your code allocates a new object.
You should switch the order of the two statements (call release first and then set to nil).
However, you don't need to alloc a new object just to keep a reference to the "selected annotation".
Declaring a regular ivar (not a retain property) and just setting it equal to the selected annotation should work.
In addition, the map view already has a property called selectedAnnotations which you should be able to use (so you don't need to maintain your own ivar or property). The map view's property is an NSArray but will always contain either 0 or 1 object(s). Be sure to check its count before accessing the object at index 0.
In fetchedData, you have several memory leaks caused by unnecessary alloc calls.
They are not needed because after calling alloc, you are then directly assigning a new reference to the pointer you just allocated memory for.
For example, userLocation is alloc'd before the for-loop but then inside the loop you directly point that variable to an object in the results array.
This means the memory that had originally been allocated for userLocation becomes abandoned with no reference to it. When you try to call release on userLocation, it is trying to release an object that was not allocated by code in fetchedData.
To fix at least userLocation, just declare the variable and don't alloc/init/release it.
The variables address and type (the NSString) have a similar issue.
I'm almost there understanding simple reference counting / memory management in Objective-C, however I'm having a difficult time with the following code. I'm releasing mutableDict (commented in the code below) and it's causing detrimental behavior in my code. If I let the memory leak, it works as expected, but that's clearly not the answer here. ;-) Would any of you more experienced folks be kind enough to point me in the right direction as how I can re-write any of this method to better handle my memory footprint? Mainly with how I'm managing NSMutableDictionary *mutableDict, as that is the big culprit here. I'd like to understand the problem, and not just copy/paste code -- so some comments/feedback is ideal. Thanks all.
- (NSArray *)createArrayWithDictionaries:(NSString *)xmlDocument
withXPath:(NSString *)XPathStr {
NSError *theError = nil;
NSMutableArray *mutableArray = [[[NSMutableArray alloc] init] autorelease];
//NSMutableDictionary *mutableDict = [[NSMutableDictionary alloc] init];
CXMLDocument *theXMLDocument = [[[CXMLDocument alloc] initWithXMLString:xmlDocument options:0 error:&theError] retain];
NSArray *nodes = [theXMLDocument nodesForXPath:XPathStr error:&theError];
int i, j, cnt = [nodes count];
for(i=0; i < cnt; i++) {
CXMLElement *xmlElement = [nodes objectAtIndex:i];
if(nil != xmlElement) {
NSArray *attributes = [NSArray array];
attributes = [xmlElement attributes];
int attrCnt = [attributes count];
NSMutableDictionary *mutableDict = [[NSMutableDictionary alloc] init];
for(j = 0; j < attrCnt; j++) {
if([[[attributes objectAtIndex:j] name] isKindOfClass:[NSString class]])
[mutableDict setValue:[[attributes objectAtIndex:j] stringValue] forKey:[[attributes objectAtIndex:j] name]];
else
continue;
}
if(nil != mutableDict) {
[mutableArray addObject:mutableDict];
}
[mutableDict release]; // This is causing bad things to happen.
}
}
return (NSArray *)mutableArray;
}
Here's an equivalent rewrite of your code:
- (NSArray *)attributeDictionaries:(NSString *)xmlDocument withXPath:(NSString *)XPathStr {
NSError *theError = nil;
NSMutableArray *dictionaries = [NSMutableArray array];
CXMLDocument *theXMLDocument = [[CXMLDocument alloc] initWithXMLString:xmlDocument options:0 error:&theError];
NSArray *nodes = [theXMLDocument nodesForXPath:XPathStr error:&theError];
for (CXMLElement *xmlElement in nodes) {
NSArray *attributes = [xmlElement attributes];
NSMutableDictionary *attributeDictionary = [NSMutableDictionary dictionary];
for (CXMLNode *attribute in attributes) {
[attributeDictionary setObject:[attribute stringValue] forKey:[attribute name]];
}
[dictionaries addObject:attributeDictionary];
}
[theXMLDocument release];
return attributeDictionaries;
}
Notice I only did reference counting on theXMLDocument. That's because the arrays and dictionaries live beyond the scope of this method. The array and dictionary class methods create autoreleased instances of NSArray and NSMutableDictionary objects. If the caller doesn't explicitly retain them, they'll be automatically released on the next go-round of the application's event loop.
I also removed code that was never going to be executed. The CXMLNode name method says it returns a string, so that test will always be true.
If mutableDict is nil, you have bigger problems. It's better that it throws an exception than silently fail, so I did away with that test, too.
I also used the relatively new for enumeration syntax, which does away with your counter variables.
I renamed some variables and the method to be a little bit more Cocoa-ish. Cocoa is different from most languages in that it's generally considered incorrect to use a verb like "create" unless you specifically want to make the caller responsible for releasing whatever object you return.
You didn't do anything with theError. You should either check it and report the error, or else pass in nil if you're not going to check it. There's no sense in making the app build an error object you're not going to use.
I hope this helps get you pointed in the right direction.
Well, releasing mutableDict really shouldn't be causing any problems because the line above it (adding mutableDict to mutableArray) will retain it automatically. While I'm not sure what exactly is going wrong with your code (you didn't specify what "bad things" means), there's a few general things I would suggest:
Don't autorelease mutableArray right away. Let it be a regular alloc/init statement and autorelease it when you return it ("return [mutableArray autorelease];").
theXMLDocument is leaking, be sure to release that before returning. Also, you do not need to retain it like you are. alloc/init does the job by starting the object retain count at 1, retaining it again just ensures it leaks forever. Get rid of the retain and release it before returning and it won't leak.
Just a tip: be sure that you retain the return value of this method when using it elsewhere - the result has been autoreleased as isn't guaranteed to be around when you need it unless you explicitly retain/release it somewhere.
Otherwise, this code should work. If it still doesn't, one other thing I would try is maybe doing [mutableArray addObject:[mutableDict copy]] to ensure that mutableDict causes you no problems when it is released.
In Memory Management Programming Guide under the topic Returning Objects from Methods (scroll down a bit), there are a few simple examples on how to return objects from a method with the correct memory managment.