VerificationController unrecognized selector iOS 5.0.1 - iphone

I just added In-App Purchasing to my iOS app and a few of my users are crashing out with
-[__NSCFString objectForKey:]: unrecognized selector sent to instance 0xf0a6f10
Obtained from BugSense, the memory location refers to the last line of this excerpt from Apple's VerificationController.m
- (BOOL)isTransactionAndItsReceiptValid:(SKPaymentTransaction *)transaction
{
if (!(transaction && transaction.transactionReceipt && [transaction.transactionReceipt length] > 0))
{
// Transaction is not valid.
return NO;
}
// Pull the purchase-info out of the transaction receipt, decode it, and save it for later so
// it can be cross checked with the verifyReceipt.
NSDictionary *receiptDict = [self dictionaryFromPlistData:transaction.transactionReceipt];
NSString *transactionPurchaseInfo = [receiptDict objectForKey:#"purchase-info"];
...
receiptDict is generated by this code (also included in VerificationController.m)
- (NSDictionary *)dictionaryFromPlistData:(NSData *)data
{
NSError *error;
NSDictionary *dictionaryParsed = [NSPropertyListSerialization propertyListWithData:data
options:NSPropertyListImmutable
format:nil
error:&error];
if (!dictionaryParsed)
{
if (error)
{
#warning Handle the error here.
}
return nil;
}
return dictionaryParsed;
}
which should return an NSDictionary or nil.
ARC is turned on. This problem seems to only occur with iOS 5.0.1 users. While I did make necessary changes to VerificationController.m, this part has been untouched. I can't seem to replicate the problem on my iPad running iOS 5.1.1, but users have said that it is persistent even after reinstalling the app. If anyone can see something simple that I'm not doing right, I'd appreciate it.
EDIT
Follow up question. What does it mean when
- (BOOL)isTransactionAndItsReceiptValid:(SKPaymentTransaction *)transaction
transaction.transactionReceipt
only provides an NSString and is it safe to ignore?

looks like to me
propertyListWithData:data options:NSPropertyListImmutableformat:nil error:&error];
return a string not a dictionary but it doesnt seems logic. are you sure the problem come from this?

Related

Overriding description method for NSObject

I'm not sure if this is a simulator issue, but I don't remeber having this problem before when I was using the iPad 5.0 simulator and below (now I'm running iPad 5.1 simulator). I overrode the description method for my Condition object to be:
- (NSString *)description {
NSString *str = [[NSString alloc] initWithFormat:#"Condition: %#", _conditionName];
return [str autorelease];
}
I have an array of these objects. My values are all valid. When I do:
for (Condition *p in self.reportsArray) {
NSLog(#"%#", [p description]);
}
It logs all my values, and then it crashes at the end. When I look at Instruments with Zombies, the last 4 calls are
-[NSPlaceHolderString initWithBytes:length:encoding:]
+[NSString stringWithUTF8String:]
-[NSAutoreleasePool release]
-[NSPlaceholderString initWithFormat:locale:arguments:]
Am I overriding description correctly?
Edit:
In Instruments, I get: message was sent to a deallocated object (zombie) at address:0x8ccf190. On the app itself, I get EXC_BAD_ACCESS.
It seems like the string returned from your description method is being released too soon.
Try rewriting your method using the stringWithFormat: class method.
- (NSString *)description {
return [NSString stringWithFormat:#"Condition: %#", _conditionName];
}
Make sure _conditionName is not a primitive.
Because the format string "%#" expects an object.

UIManagedDocument - Validating Core Data Entity

I have an app that uses Core Data and it gets its ManagedObjectContext by using UIManagedObject. From reading, I see that I am not suppose to save the context directly - rather I should depend on autosaving of UIManagedObject or use saveToURL:... My issue is that I want to validate the data being stored in my entity. I have constraints on the entity that specify that the min length for the string properties is 1. However, I can create a new object, assign its properties empty strings, and save the file. In the completion handler of saveToURL:... it always has a true success value. I then created my own validator for the name property of my entity. I used sample code from the Core Data Programming Guide -
-(BOOL)validateName:(id *)ioValue error:(__autoreleasing NSError **)outError
{
if (*ioValue == nil)
{
if (outError != NULL)
{
NSString *errorStr = #"nil error";
NSDictionary *userInfoDict = [NSDictionary dictionaryWithObject:errorStr
forKey:NSLocalizedDescriptionKey];
NSError __autoreleasing *error = [[NSError alloc] initWithDomain:#"domain"
code:1
userInfo:userInfoDict];
*outError = error;
}
return NO;
}
else if( [*ioValue length] == 0 )
{
if (outError != NULL) {
NSString *errorStr = #"length error";
NSDictionary *userInfoDict = [NSDictionary dictionaryWithObject:errorStr
forKey:NSLocalizedDescriptionKey];
NSError __autoreleasing *error = [[NSError alloc] initWithDomain:#"domain"
code:1
userInfo:userInfoDict];
*outError = error;
}
return NO;
}
else
{
return YES;
}
}
When this runs, I see that the ioValue has 0 length and that it returns NO, but then my completion handler is never called. Any help would be great.
Is there something I am missing for how to handle saving errors with UIManagedDocument - particularly how to notify the calling code that an error happened while saving its information.
As a rule, you should only call saveToURL to create a brand new file. Let auto-save do the rest.
Also, I'm not sure I follow your question. If you are asking how to know about save failures, the best you can do is register for notifications (since all saves happen on a background thread).
Directly from the documentation:
A UIDocument object has a specific state at any moment in its life cycle. You can check the current state by querying the documentState property. And you can be notified of changes in the state of a document by observing the UIDocumentStateChangedNotification notification.
I guess I need to implement handleError:(NSError *)error userInteractionPermitted:(BOOL)userInteractionPermitted in a subclass of the UIManagedDocument. I found that via this article - http://blog.stevex.net/2011/12/uimanageddocument-autosave-troubleshooting/

NSMutableArray to NSDictionary iOS 3.1.3 problem

I have a problem when I try to run my app on an iOS 3.1.3
I run my app in 4.1 and theres is no problem, but with 3.1.3 my app crash.
My app crash in this line:
NSDictionary *atm= (NSDictionary *)[atmData objectAtIndex:0];
And here is a piece of my code:
DataHelper *mydata = [[DataHelper alloc] init];
NSMutableArray *atmData = [mydata getAllAtmByLocation:appDelegate.userLocation];
if(atmData != nil){
NSDictionary *atm= (NSDictionary *)[atmData objectAtIndex:0];
//...
}
Like I said this issue happens only on iOS 3.1.3, in 4.1 it works perfectly.
Thx for ur help!!
I am guessing you're getting a subscript out of range error. Is it possible that getAllAtmByLocation:is returning an empty array? You might change your conditional to:
if (atmData != nil && [atmData count] > 0) {
...
}
Check your [atmData count] and make sure the array actually contains an element. Maybe whatever you're using to populate the array isn't supported in 3.1.3.

How can I use NSError in my iPhone App?

I am working on catching errors in my app, and I am looking into using NSError. I am slightly confused about how to use it, and how to populate it.
Could someone provide an example on how I populate then use NSError?
Well, what I usually do is have my methods that could error-out at runtime take a reference to a NSError pointer. If something does indeed go wrong in that method, I can populate the NSError reference with error data and return nil from the method.
Example:
- (id) endWorldHunger:(id)largeAmountsOfMonies error:(NSError**)error {
// begin feeding the world's children...
// it's all going well until....
if (ohNoImOutOfMonies) {
// sad, we can't solve world hunger, but we can let people know what went wrong!
// init dictionary to be used to populate error object
NSMutableDictionary* details = [NSMutableDictionary dictionary];
[details setValue:#"ran out of money" forKey:NSLocalizedDescriptionKey];
// populate the error object with the details
*error = [NSError errorWithDomain:#"world" code:200 userInfo:details];
// we couldn't feed the world's children...return nil..sniffle...sniffle
return nil;
}
// wohoo! We fed the world's children. The world is now in lots of debt. But who cares?
return YES;
}
We can then use the method like this. Don't even bother to inspect the error object unless the method returns nil:
// initialize NSError object
NSError* error = nil;
// try to feed the world
id yayOrNay = [self endWorldHunger:smallAmountsOfMonies error:&error];
if (!yayOrNay) {
// inspect error
NSLog(#"%#", [error localizedDescription]);
}
// otherwise the world has been fed. Wow, your code must rock.
We were able to access the error's localizedDescription because we set a value for NSLocalizedDescriptionKey.
The best place for more information is Apple's documentation. It really is good.
There is also a nice, simple tutorial on Cocoa Is My Girlfriend.
I would like to add some more suggestions based on my most recent implementation. I've looked at some code from Apple and I think my code behaves in much the same way.
The posts above already explain how to create NSError objects and return them, so I won't bother with that part. I'll just try to suggest a good way to integrate errors (codes, messages) in your own app.
I recommend creating 1 header that will be an overview of all the errors of your domain (i.e. app, library, etc..). My current header looks like this:
FSError.h
FOUNDATION_EXPORT NSString *const FSMyAppErrorDomain;
enum {
FSUserNotLoggedInError = 1000,
FSUserLogoutFailedError,
FSProfileParsingFailedError,
FSProfileBadLoginError,
FSFNIDParsingFailedError,
};
FSError.m
#import "FSError.h"
NSString *const FSMyAppErrorDomain = #"com.felis.myapp";
Now when using the above values for errors, Apple will create some basic standard error message for your app. An error could be created like the following:
+ (FSProfileInfo *)profileInfoWithData:(NSData *)data error:(NSError **)error
{
FSProfileInfo *profileInfo = [[FSProfileInfo alloc] init];
if (profileInfo)
{
/* ... lots of parsing code here ... */
if (profileInfo.username == nil)
{
*error = [NSError errorWithDomain:FSMyAppErrorDomain code:FSProfileParsingFailedError userInfo:nil];
return nil;
}
}
return profileInfo;
}
The standard Apple-generated error message (error.localizedDescription) for the above code will look like the following:
Error Domain=com.felis.myapp Code=1002 "The operation couldn’t be completed. (com.felis.myapp error 1002.)"
The above is already quite helpful for a developer, since the message displays the domain where the error occured and the corresponding error code. End users will have no clue what error code 1002 means though, so now we need to implement some nice messages for each code.
For the error messages we have to keep localisation in mind (even if we don't implement localized messages right away). I've used the following approach in my current project:
1) create a strings file that will contain the errors. Strings files are easily localizable. The file could look like the following:
FSError.strings
"1000" = "User not logged in.";
"1001" = "Logout failed.";
"1002" = "Parser failed.";
"1003" = "Incorrect username or password.";
"1004" = "Failed to parse FNID."
2) Add macros to convert integer codes to localized error messages. I've used 2 macros in my Constants+Macros.h file. I always include this file in the prefix header (MyApp-Prefix.pch) for convenience.
Constants+Macros.h
// error handling ...
#define FS_ERROR_KEY(code) [NSString stringWithFormat:#"%d", code]
#define FS_ERROR_LOCALIZED_DESCRIPTION(code) NSLocalizedStringFromTable(FS_ERROR_KEY(code), #"FSError", nil)
3) Now it's easy to show a user friendly error message based on an error code. An example:
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:FS_ERROR_LOCALIZED_DESCRIPTION(error.code)
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
Great answer Alex. One potential issue is the NULL dereference. Apple's reference on Creating and Returning NSError objects
...
[details setValue:#"ran out of money" forKey:NSLocalizedDescriptionKey];
if (error != NULL) {
// populate the error object with the details
*error = [NSError errorWithDomain:#"world" code:200 userInfo:details];
}
// we couldn't feed the world's children...return nil..sniffle...sniffle
return nil;
...
Objective-C
NSError *err = [NSError errorWithDomain:#"some_domain"
code:100
userInfo:#{
NSLocalizedDescriptionKey:#"Something went wrong"
}];
Swift 3
let error = NSError(domain: "some_domain",
code: 100,
userInfo: [NSLocalizedDescriptionKey: "Something went wrong"])
Please refer following tutorial
i hope it will helpful for you but prior you have to read documentation of NSError
This is very interesting link i found recently ErrorHandling
I'll try summarize the great answer by Alex and the jlmendezbonini's point, adding a modification that will make everything ARC compatible (so far it's not since ARC will complain since you should return id, which means "any object", but BOOL is not an object type).
- (BOOL) endWorldHunger:(id)largeAmountsOfMonies error:(NSError**)error {
// begin feeding the world's children...
// it's all going well until....
if (ohNoImOutOfMonies) {
// sad, we can't solve world hunger, but we can let people know what went wrong!
// init dictionary to be used to populate error object
NSMutableDictionary* details = [NSMutableDictionary dictionary];
[details setValue:#"ran out of money" forKey:NSLocalizedDescriptionKey];
// populate the error object with the details
if (error != NULL) {
// populate the error object with the details
*error = [NSError errorWithDomain:#"world" code:200 userInfo:details];
}
// we couldn't feed the world's children...return nil..sniffle...sniffle
return NO;
}
// wohoo! We fed the world's children. The world is now in lots of debt. But who cares?
return YES;
}
Now instead of checking for the return value of our method call, we check whether error is still nil. If it's not we have a problem.
// initialize NSError object
NSError* error = nil;
// try to feed the world
BOOL success = [self endWorldHunger:smallAmountsOfMonies error:&error];
if (!success) {
// inspect error
NSLog(#"%#", [error localizedDescription]);
}
// otherwise the world has been fed. Wow, your code must rock.
Another design pattern that I have seen involves using blocks, which is especially useful when a method is being run asynchronously.
Say we have the following error codes defined:
typedef NS_ENUM(NSInteger, MyErrorCodes) {
MyErrorCodesEmptyString = 500,
MyErrorCodesInvalidURL,
MyErrorCodesUnableToReachHost,
};
You would define your method that can raise an error like so:
- (void)getContentsOfURL:(NSString *)path success:(void(^)(NSString *html))success failure:(void(^)(NSError *error))failure {
if (path.length == 0) {
if (failure) {
failure([NSError errorWithDomain:#"com.example" code:MyErrorCodesEmptyString userInfo:nil]);
}
return;
}
NSString *htmlContents = #"";
// Exercise for the reader: get the contents at that URL or raise another error.
if (success) {
success(htmlContents);
}
}
And then when you call it, you don't need to worry about declaring the NSError object (code completion will do it for you), or checking the returning value. You can just supply two blocks: one that will get called when there is an exception, and one that gets called when it succeeds:
[self getContentsOfURL:#"http://google.com" success:^(NSString *html) {
NSLog(#"Contents: %#", html);
} failure:^(NSError *error) {
NSLog(#"Failed to get contents: %#", error);
if (error.code == MyErrorCodesEmptyString) { // make sure to check the domain too
NSLog(#"You must provide a non-empty string");
}
}];
extension NSError {
static func defaultError() -> NSError {
return NSError(domain: "com.app.error.domain", code: 0, userInfo: [NSLocalizedDescriptionKey: "Something went wrong."])
}
}
which I can use NSError.defaultError() whenever I don't have valid error object.
let error = NSError.defaultError()
print(error.localizedDescription) //Something went wrong.
Well it's a little bit out of question scope but in case you don't have an option for NSError you can always display the Low level error:
NSLog(#"Error = %# ",[NSString stringWithUTF8String:strerror(errno)]);

Iphone App Crashes - But sometime works(50%-50%)

I am using following code for showing a next view(tableview) in Iphone app.
It sometime works and some time app crashes without any exception log
NSLog(#"Ok"); is log everytime
50% attempts application crashes
-(IBAction)statusInitiationButAction:(id)sender{
#try {
NSArray *tempArrIniId = [eventInitiationArray valueForKey:#"act_id"];
int s;
if([tempArrIniId containsObject:selectedInitiateId]){
s=[tempArrIniId indexOfObject:selectedInitiateId];
}
[tempArrIniId release];
NSString *selStatusId = [NSString stringWithString:[[eventInitiationArray objectAtIndex:s] objectForKey:#"status_id"]];
for (int i=0; i<[statusInitiationArray count]; i++) {
id statusDict = [statusInitiationArray objectAtIndex:i];
if ([selStatusId intValue] == [[statusDict objectForKey:#"id"] intValue]) {
[statusDict setValue:#"1" forKey:#"selected"];
[statusInitiationArray replaceObjectAtIndex:i withObject:statusDict];
}else {
[statusDict setValue:#"0" forKey:#"selected"];
[statusInitiationArray replaceObjectAtIndex:i withObject:statusDict];
}
}
NSLog(#"statusInitiationTable...%#",statusInitiationArray);
[statusInitiationTable.tableView reloadData];
[[self navigationController] pushViewController:statusInitiationTable animated:YES];
NSLog(#"ok");
}#catch (NSException * e) {
NSLog(#"statusInitiationButAction....%#",e);
}
}
Can anybody guide me about the problem.
Thanks
Amit Battan
You should not be doing this:
[tempArrIniId release];
Because in this line...
NSArray *tempArrIniId = [eventInitiationArray valueForKey:#"act_id"];
...you are not creating the tempArrIniId you are merely obtaining a reference to it. Therefore, you did not retain it and have no need to release it.
You are getting an intermittent crash because your over releasing the object pointed to by tempArrIniId while that object is still a member of the eventInitiationArray. When the array tries to access the object or even count itself, it crashes because there is not an object where it expects one to be. That crash can happen anywhere in the app where the 'eventInitiationArray' is used.
Overzealous releasing causes more problems than it prevents. When in doubt, don't release. It's trivial to find memory leaks with the analysis tools if you don't release something you should have and it's trivial to fix it.
It's a lot harder to track down a crash caused by over releasing an object held by other objects such as arrays because the subsequent crash can occur far from where the over release occurred.