I have the following code in my .m file:
- (IBAction)LoginButton:(id)sender {
// create string contains url address for php file, the file name is phpFile.php, it receives parameter :name
NSString *strURL = [NSString stringWithFormat:#"http://www.myURL.com/verify.php?Email=%#",Email.text];
// to execute php code
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
// to receive the returend value
NSString *strResult = [[[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding]autorelease];
NSLog(#"%#", strResult);
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Result:"
message:strResult
delegate:nil
cancelButtonTitle:#"Okay"
otherButtonTitles:nil];
[alert show];
}
And I am getting that autorelease is unavailable in automatic reference counting mode.
It seems to be an issue with the following line:
NSString *strResult = [[[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding]autorelease];
How can I solve this?
Just delete the autorelease call; if you are using ARC (Automatic Reference Counting) you don't need to worry about memory management.
Related
bit of a beginner here and I've been stuck on something all day!
I've got 2 Parse Tables: a User (which works perfectly for logging in etc) and a UserStats that holds variables (in this case the User's Level as the first column)
All I want to do is retrieve the User's current level and display it in a label in Xcode. I've done lots of research but I cannot work out where I've gone wrong.
I'm using this Query in my .m:
- (void) retrieveFromParse {
PFQuery query = [PFQuery queryWithClassName:#"UserStats"];
[query whereKey:#"User" equalTo:[PFUser currentUser]];
[query getFirstObjectInBackgroundWithBlock:(PFObjectobject, NSError *error)
{
if (!object)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Oh No!" message:#"Could not locate value!" delegate:self cancelButtonTitle:#"Okay" otherButtonTitles:nil];
[alert show];
}
else
{
int Level = [[object objectForKey:#"Level"] intValue];
[_newlabel setText:[NSString stringWithFormat:#"%d", Level]];
}
}];
}
and my .h looks like this:
import <UIKit/UIKit.h>
import <Parse/Parse.h>
#interface ShowLevel : UIViewController
#property (weak, nonatomic) IBOutlet UILabel *newlabel;
#end
Edit: I've turned on exception breakpoints and it's highlighting:
[query getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) {
What is the actual error that you are getting? Also you have to do anything that has to do with UI on the main thread. The query is actually running on the background thread and you are either showing alertView or updating a label which you have to do on the main thread. Add dispatch_async(dispatch_get_main_queue(), ^{ }); to your code where you are doing UI
if (!object)
{
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Oh No!" message:#"Could not locate value!" delegate:self cancelButtonTitle:#"Okay" otherButtonTitles:nil];
[alert show];
});
}
else
{
int Level = [[object objectForKey:#"Level"] intValue];
dispatch_async(dispatch_get_main_queue(), ^{
[_newlabel setText:[NSString stringWithFormat:#"%d", Level]];
});
}
This has since been resolved. I used the .m code:
PFQuery *query = [PFQuery queryWithClassName:#"UserStats"];
PFObject *Object = [query getObjectWithId:#"fghsd7fddhf"];
level = [[Object objectForKey:#"Level"] intValue];
[levelLabel setText:[NSString stringWithFormat:#"%i", level]];
While it's only temporary since I'll need to change it to point to values without specifying objectId, this works nicely for testing. Thanks to everyone who provided help :)
I have a Mac application that is supposed to fetch Twitter followers and friends for a given username and then, in turn, ask Twitter for the user NAMES for each of those returned UserIDs. As you can see below, I have a method that will call the Twitter API to get friends/followers (which works fine). It is the userNameForUserID:delegate: method that is causing me problems. I used to do these requests synchronously and return the NSString for the username right then. That (now commented out) line always broke, so I tried doing it with an NSURLConnection asynchronously. Still doesn't work. I don't understand why
[[NSString alloc] initWithContentsOfURL:...] works for the fetchFollowers... method, but not when I do it the EXACT SAME way in the other...
I put a break point on the line that used to alloc init the NSString with contents of URL, and when I step into it, it doesn't break, return, throw an exception, crash...nothing. It's as if that line just got stepped over (but my application is still blocked.
Any ideas? Much appreciated!
NSString * const GET_FOLLOWERS = #"https://api.twitter.com/1/followers/ids.json?cursor=-1&screen_name=";
NSString * const GET_FRIENDS = #"https://api.twitter.com/1/friends/ids.json?cursor=-1&screen_name=";
NSString * const GET_USER_INFO = #"https://api.twitter.com/1/users/show.json?user_id=";
#implementation TwitterAPI
+ (void)userNameForUserID:(NSNumber *)userID delegate:(id<UserNameDelegate>)delegate
{
NSURL *url = [NSURL URLWithString:[GET_USER_INFO stringByAppendingString:[userID stringValue]]];
// NSString *JSON = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:req queue:queue completionHandler:^(NSURLResponse *urlResponse, NSData *data, NSError *error) {
[delegate addUserNameToArray:data];
}];
}
+ (NSArray *)fetchFollowersWithUserName:(NSString *)userName
{
NSURL *url = [NSURL URLWithString:[GET_FOLLOWERS stringByAppendingString:userName]];
NSArray *followerIDs;
NSString *JSON = [[NSString alloc] initWithContentsOfURL:url encoding:NSASCIIStringEncoding error:nil];
if ([JSON rangeOfString:#"error"].location == NSNotFound)
followerIDs = [[JSON JSONValue] valueForKey:#"ids"];
return followerIDs;
}
When I run my app in Xcode using the simulator it runs just file until I add in the first three lines involving the text file. It gives me a message saying terminate called after throwing an instance of 'NSException'. I don't know what that means or why it only happens when I try to read in the text file and display it in the textView.
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"textfiles/brain_01" ofType:#"txt"];//establish file path for text file
NSString *textFile = [[NSString alloc] stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error: nil];
textView.text = textFile;
[super viewDidLoad];
fullButton.hidden = YES;
viewLabel.hidden = YES;
}
NSException means your code has a bug in it. An exception is an error. In your case, it's probably because
NSString *textFile = [[NSString alloc] stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error: nil];
should be
NSString *textFile = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error: nil];
stringWithContentsOfFile is a class method used to make NSString -- only use alloc with init... methods.
NSURL *url;
NSData *data;
NSString *blork;
url = [NSURL URLWithString: #"http://www.mycompanyaddress.com/identity_check.jsp?cliId=A-00000&security_key=00000"];
data = [url resourceDataUsingCache: NO];
blork = [[NSString alloc] initWithData: data encoding: NSASCIIStringEncoding];
UIAlertView *testMessage = [[UIAlertView alloc] initWithTitle: #"From Server: " message: blork delegate: self cancelButtonTitle: #"Ok" otherButtonTitles: nil];
[testMessage show];
[testMessage release];
RESOURCEDATAUSINGCACHE is now a deprecated function..otherwise it worked like a charm
you can use -
NSData *data = [NSData dataWithContentsOfURL:url];
and as document says
Use NSURLConnection instead of this method.
Hi I set up my own coredata app, or I tried...
First I created the xdatamodel and generated the Modelclasses, after this I implemented all the function of core-data in AppDelegate which I found in a generated project. Finally I copied the fetchedResultsController in my TableViewController.
fetchedResultsController
- (NSFetchedResultsController *)fetchedResultsController {
if (fetchedResultsController_ != nil) {
return fetchedResultsController_;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"ParameterGroup" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
[fetchRequest setFetchBatchSize:20];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:#"Root"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
[aFetchedResultsController release];
[fetchRequest release];
[sortDescriptor release];
[sortDescriptors release];
NSError *error = nil;
if (![fetchedResultsController_ performFetch:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return fetchedResultsController_;
}
First I checked if the managedObjectsController is != nil, it has a address
Then I copied the EntityName from my xdatamodel in entityForName,
but NSEntityDescricption entity is nil.
And if I just create a new object the exception says, that the entity doesn't exist
Do I have to connect the xdatamodel to my project?
Hope you can help me
Thanks a lot!!!
The most common cause of this problem is simply misspelling the entity name wrong in the code such that it doesn't match the entity name in the data model.
Copy and paste the entity name from the model to the code and see if that fixes the problem.
The simplest way to solve this, given that you haven't done a lot coding on non-core-data parts, is probably to create a new project where you check the box for "Use Core Data". If you're going to use a Navigation Bar, choose this as your template. If I recall correctly, this will generate a table view with all functions needed. You'll have to modify the datamodel (generated).
Remark that you'll have to delete the app from the Simulator if it is installed and you change the datamodel (otherwise the generated data will not be consistent with the datamodel and the app will crash)