objective-c,memory-management,objective-c-blocks , Clarifications needed for a crash using NSArray, blocks and Manual Reference Counting


Clarifications needed for a crash using NSArray, blocks and Manual Reference Counting

Question:

Tag: objective-c,memory-management,objective-c-blocks

I need some clarifications on a crash I'm encountering using NSArray, blocks and Manual Reference Counting. My goal is to store blocks on a collection (NSArray in this case) in order to reuse them in the future.

I've setup a small sample to replicate the issue. In particular, I have a class Item that looks like the following:

#import <Foundation/Foundation.h>

typedef void(^MyBlock)();

@interface Item : NSObject

- (instancetype)initWithBlocks:(NSArray*)blocks;

@end

#import "Item.h"

@interface Item ()

@property (nonatomic, strong) NSArray *blocks;

@end

@implementation Item

- (instancetype)initWithBlocks:(NSArray*)blocks
{
    self = [super init];
    if (self) {

        NSMutableArray *temp = [NSMutableArray array];
        for (MyBlock block in blocks) {
            [temp addObject:[[block copy] autorelease]];
        }

        _blocks = [temp copy];            
    }
    return self;
}

The usage is described below (I'm using in the app delegate).

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {

    __block typeof(self) weakSelf = self;

    MyBlock myBlock1 = ^() {
        [weakSelf doSomething1];
    };

    MyBlock myBlock2 = ^() {
        [weakSelf doSomething1];
    };

    NSArray *blocks = @[myBlock1, myBlock2];

    // As MartinR suggested the code crashes even
    // if the following line is commented
    Item *item = [[Item alloc] initWithBlocks:blocks];
}

If I run the app, it crashes with an EXC_BAD_INSTRUCTION (note that I've already enabled All Exceptions breakpoints). In particular, the app stops in the main.

int main(int argc, const char * argv[]) {
    return NSApplicationMain(argc, argv);
}

Note: As suggested by Ken Thomases, if you use bt command on llvm console, you are to see the back trace. In this case it shows the following:

-[__NSArrayI dealloc]

If I comment the [weakSelf doSomethingX]; it works without crashes (it does not mean that is correct).

Modifying the code a little bit like the following, all runs ok.

// Item does not do anymore the copy/autorelease dance
// since used in the declaration of the blocks
- (instancetype)initWithBlocks:(NSArray*)blocks
{
    self = [super init];
    if (self) {

        _blocks = [blocks retain];

    }
    return self;
}

and

__block typeof(self) weakSelf = self;

MyBlock myBlock1 = [[^() {
    [weakSelf doSomething1];
} copy] autorelease];

MyBlock myBlock2 = [[^() {
    [weakSelf doSomething1];
} copy] autorelease];

NSArray *blocks = @[myBlock1, myBlock2];

Item *item = [[Item alloc] initWithBlocks:blocks];

What is the point here? I think I'm missing something but I don't know what.

Update 1

Ok. I'll try to recap my thoughts based on the comments with @Martin R and @Ken Thomases.

A block, by default, is created on stack if a copy message is not sent to it (ARC does this for us) in order to move it on the heap. So, the situation in this case is the following. I create an autorelease array and I add two blocks where retain is called in a implicit manner. When the applicationDidFinishLaunching method finishes is execution, the blocks, since created on the stack (they are automatic variables) disappear. In a later moment, the array called blocks will be released since has been marked as autorelease. So, it will crash since it will send a release object to blocks that do not exist anymore.

So, my question is the following: What does it mean to send a retain message to a block that is on the stack? Why the array is the source of the crash (see the back trace)? In other words, since a block is on the stack, will it bump the retain count of it? And when it goes out of scope? In addiction, why if I comment the [weakSelf doSomething1] line the code works without problems? Not very clear to me this part.


Answer:

You are sticking an object from the stack into an autoreleased array. BOOM ensues.

Consider:

typedef void(^MyBlock)();

int main(int argc, char *argv[]) {
        @autoreleasepool {
          NSObject *o = [NSObject new];
          MyBlock myBlock1 = ^() {
            [o doSomething1];
          };
          NSLog(@"o %p", o);
          NSLog(@"b %p", myBlock1);
          NSLog(@"b retain %p", [myBlock1 retain]);
          NSLog(@"b copy %p", [myBlock1 copy]);
          NSLog(@"s %p", ^{});
          sleep(1000000);
        }
}

Compiled/run as -i386 (because the #s are smaller and more obvious):

a.out[11729:555819] o 0x7b6510f0
a.out[11729:555819] b 0xbff2dc30
a.out[11729:555819] b retain 0xbff2dc30
a.out[11729:555819] b copy 0x7b6511a0
a.out[11748:572916] s 0x67048

Since the object is at 0x7b, we can assume that is the heap. 0xb is really high memory and, thus, the stack.

The retain doesn't cause a copy (because doing so would have invariably led to leaks) and retain on a stack based object is meaningless.


If you change the [o doSomething1]; to [nil doSomething1]; then that becomes a static block and that lives in readonly mapped memory (readonly-executable pages from the mach-o's TEXT segment) and, thus, there is no allocation to deallocate and retain/release/autorelease are no-ops.

As you can see, the static block ended up around 0x67048 (this number may change from run to run, btw, for a variety of reasons. Low in memory.

In fact, because of the sleep(), we can run vmmap against the a.out process and see:

==== Writable regions for process 11772
REGION TYPE              START - END     [ VSIZE] PRT/MAX SHRMOD  REGION DETAIL
__DATA                 00067000-00068000 [    4K] rw-/rwx SM=ZER  /tmp/a.out

That is, the static block was in the first 4K segment of mapped writable regions from the mach-o file. Note that this doesn't mean the code is in that writable region (SECURITY HOLE if it were). The code is in the TEXT segment mapped into the readable regions.


Related:


How to prevent duplicate entry on parse?


ios,objective-c,iphone,swift,parse.com
I' trying to save song info to parse, but if the song already exist in parse I want my code just do nothing. I've tried this code below: var Music = PFObject(className:"Musics") var query = PFQuery(className:"Musics") query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in if error == nil {...

drawing views after time intervals


ios,objective-c
I need to draw views after time interval for example creating the first view then wait 5 second and create the other one, I am using this: -(void) drawView { int x=0; x+=16; UIView *view = [[UIView alloc] initWithFrame:CGRectMake(x, 580, 16, 25)]; view.backgroundColor = [UIColor blackColor]; [self.view addSubview:view]; } [self...

When replicating UIAlertView; background is not the same


ios,objective-c,uiview,uialertview
I'm creating a custom UIAlertView (from a UIView). I'm trying to get the same background effect (when the background view darkens). So I created a new black UIView with .5 opacity, and added it to the background. The problem is, I have a tab bar. When the black UIView covers...

It is possible to continuously update the UILabel text as user enter value in UITextField in iOS


ios,objective-c,swift,uitextfield,uilabel
In my application i have one UILabel and UITextField. Initially UILabel text in nil. As soon as user enter some text in UITextField my UILabel text also Update. Let say When user enter A in UITextField my UILabel immediately show A, B in UITextField my UILabel show B and so...

Updating Core Data Model using two separate View Controllers


ios,objective-c,uitableview,core-data
I originally had my app setup to store one line items in a single entity within my core data model. I have since decided to change this to allow the main uitableview to simply list the name of each item and then when you tap on an item you can...

Multiple NSURLSessions Causing UITableView Problems


ios,objective-c,uitableview,nsurlsession
I'm running into a bit of a strange problem here. One of my NSURLSessions is in charge of getting information for restaurant information that I have stored (restaurant name, restaurant's logo URL, etc), and then the second NSURLSession is in charge of using the restaurant's logo URL to retrieve the...

iOS: What is the callback when tapped on the empty space between keyboard and search bar to dismiss the keyboard when search bar is active


ios,objective-c,swift
I have SearchController for my TableViewController. I wanted to perform some actions when user taps on the empty space on the screen (between the keyboard and search bar) to dismisses the keyboard and displays the main Table View.

iPod Touch (5th gen) 'Source type 1 not available' crash when using UIImagePickerControllerSourceTypeCamera


ios,objective-c,ipod-touch
The iPod Touch (5th gen) has both a front and rear camera so why does my app crash when i try to present a UIImagePickerController with sourceType: UIImagePickerControllerSourceTypeCamera - (void)openImagePickerType:(NSString *)type { UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init]; imagePicker.delegate = self; if([type isEqualToString:kImagePickerCameraString]) imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera; if([type isEqualToString:kImagePickerLibraryString]) imagePicker.sourceType =...

how to share screenshot to Facebook


objective-c,facebook,facebook-sdk-4.0,social-media
I've already done that screenshot part, but still haven't found any solution to share the screenshot image to Facebook by using FBSDKSharePhoto. Facebook doesn't provide enough references for it. Can anyone please guide me here? Here is my screenshot code just in case: CGRect screenRect = [[UIScreen mainScreen] bounds]; UIGraphicsBeginImageContextWithOptions(screenRect.size,...

NS_ENUM as property in protocol


ios,objective-c,automatic-ref-counting
I came across to strange behaviour. I used to have: @property (nonatomic) ApplicationState applicationState; directly in my Application class. Now it's extracted to protocol @protocol ApplicationProtocol <NSObject> @property (nonatomic) ApplicationState applicationState; ApplicationState is Enum typedef NS_ENUM(NSUInteger, ApplicationState) { ApplicationStateNormal = 0, ApplicationStateExpanded = 1, ApplicationStateMaximized = 2 }; Now. It...

Call function on Server from iOS app - Objective C


ios,objective-c,json,server,backend
If you are familiar with Parse.com's Javascript SDK, this is what I am trying to do for my own server for my iOS app (Objective-c). I want to be able to send some a string to the function that is on my server, have the server run its function and...

Build error after I localized Info.plist


ios,objective-c,xcode,swift,localization
I localized Info.plist : And I got this build error : error: could not read data from '/Users/cherif/Apps/Wesh/Info.plist': The file “Info.plist” couldn’t be opened because there is no such file. Actually there are now two Info.plist files : fr.lproj/Info.plist Base.lproj/Info.plist How to localize the Info.plist path ?...

memory content not erased after deleting my pointer (on a simple example) [duplicate]


c++,pointers,memory-management
This question already has an answer here: Can a local variable's memory be accessed outside its scope? 16 answers Here is a simple of example of a question I have: I create a pointer of integer (value 5), I print the pointer (hence the address) of the memory case...

Assigning a variable from another class


ios,objective-c,methods,protocols
I have a UIView with a UIButton created in 1 class: "viewClass". In my mainVC class, I called viewClas and I needed to call a method in mainVc when the button is selected, so I created a protocol. (I hope that was clear.) Here's how I set up the protocol...

starting to work with iOS push notifications


ios,objective-c,push-notification
i started following this tutorial i found via google. http://code.tutsplus.com/tutorials/setting-up-push-notifications-on-ios--cms-21925 However i got stuck on basically the first step where it said that the methods are deprecated, i changed them to the ones suggested by Xcode the original code was [application registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)]; i changed it to...

What is the best practice add video background view?


ios,objective-c,swift,video
I want to add background view with video (or gif) like in app "Uber" I'd like to use video background view for a long time in my app. And I want to know the answers to these questions: What of them will consume less battery energy Can I use it...

Setting delegates (for protocols) only works in prepareForSegue?


ios,objective-c,delegates,protocols
Most of the information I found involving implementing protocols and delegates involves a step where you do this; DestinationViewController *destinationVC = [[destinationViewController alloc] init]; destinationVC.delegate = self; But after hours of frustration because I couldn't get it to work I finally stumbled across another way to allocate the destinationVC in...

How to do a “show (e.g Push)” segue programatically without animation?


ios,objective-c,swift,storyboard,segue
How can I do a "show (e.g Push)" segue programatically without animation? None of the solutions I've found works the same way as the one in storyboard.

Set NSObject property - EXC_BAD_ACCESS


ios,objective-c,exc-bad-access,nsobject
Process : App is on the home view controller and is requesting data on API to set an NSObject property. The request is processing on a private method. User change the view controller to a second view controller (the request is still processing asynchronously) The second view controller is loaded...

NSPredicate crash with path which contains square brackets


objective-c,cocoa,nspredicate
I have to search paths which contains square brackets in it from core data. But when I trying to create search query like below, xcode crashes. path == /my/local/[path] I've tried to escape square brackets, from one brackets to 16 brackets, but nothing works. That path is from another application,...

Progressive HMAC SHA256 in Objective-C


javascript,objective-c,cryptography,hmac,cryptojs
I need to generate a hash using HMAC SHA256. I am using the following code in JavaScript. I need an equivalent code in Objective-C. function serialize( obj ) { return Object.keys(obj).reduce(function(a,k){a.push(k+'='+encodeURIComponent(obj[k]));return a},[]).join('&') } var query = { Action : 'MyAction', SignatureMethod : 'HmacSHA256', }; var hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, 'MYVALUE'); var...

Using sockets to build real time chat for iOS?


ios,objective-c,sockets,chat,real-time
If I wanted to build a real time chat app for iOS using Objective-C, what would be the best way of going about it?

Difference between stringByAppendingString and appendString in ios


ios,objective-c,swift,nsstring,nsmutablestring
What is the difference between stringByAppendingString and appendString? If NSString is not mutable then how could it append string?

Google Drive API (GTL) - Create multiple folder paths in order?


ios,objective-c,swift,google-drive-sdk,google-api-objc-client
I'm using the Google APIs Client Library for Objective-C (GTL) to access the Google Drive API. According to it's Introduction to the Google APIs Client Library for Objective-C, Query execution by the service is inherently asynchronous. Which means when you try to create a path like: root/a/b/c, before you can...

Override UITabBarController Icon Selection


ios,objective-c,uitabbarcontroller
I'm using a standard UITabBarController with icons at the bottom, each bringing to it's ownViewController. My question is basically: Is there a way to override what happens when an icon is selected rather then directly bringing them to the view? Reason being is because I'm adding a login screen to...

How to push a view from project that based on Tab Bar Controller


objective-c
I have a project based on Tab Bar Controller. BUT There is one view that I has to be pushed from a button in View which belong to Tab bar controller. This is very crazy for me that I can not push the view because that last view is not...

Set background color of .xib launch image background


objective-c
I need a specific hex code to be background color, not drop down from a list of pre-made choices. How do I accomplish this?

Crash when processing `__Atom` class object in Objective C (using Objective C runtime )


objective-c,osx,objective-c-runtime
Hi I'm using this answer to get list of class to automatically build some structure. My code looks like that: NSMutableDictionary *result = [NSMutableDictionary dictionaryWithCapacity: 32]; Class* classes = NULL; int numClasses = objc_getClassList(NULL, 0); if (numClasses > 0 ) { classes = (Class*)malloc(sizeof(Class) * numClasses); numClasses = objc_getClassList(classes, numClasses);...

Xcode UIWebView not changing page with changed URL


ios,objective-c,xcode,uiwebview
I'm automatically generating a NSURL based on the distance of a pan gesture on the screen (long story...). Anyways, I'm having no problem generating the URL. The URL dynamically changes, and then I have an NSTimer that repeats every second which tells a UIWebView to reload with the new URL....

Disadvantages of calling realloc in a loop


c,memory-management,out-of-memory,realloc
I'm trying to implement some math algorithms in C on Windows 7, and I need to repeatedly increase size of my array. Sometimes it fails because realloc can't allocate memory. But if I allocate a lot of memory at once in the beginning it works fine. Is it a problem...

Trying to dismiss a popover view controller with a table view inside of it


ios,objective-c,uipopovercontroller
I'm trying to dismiss a popover when selecting a cell inside of it. I have created a custom delegate to support this however it is not working: In my class that houses the PopOver and table View I have the following: In .h: @protocol DismissDelegate <NSObject> -(void)didTap; @end @interface AssistanceNeededAtPopOverViewController...

After an insert into the UITableView : custom the cell


ios,objective-c,uitableview
I'm using insertion into my UITableView with this : Skill * newSkill = [[Skill alloc] init]; newSkill.name = @"Nouvelle compétence"; newSkill.pathPicto = @"generic"; [self.skills insertObject:newSkill atIndex:0]; NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; [self.tableView beginUpdates]; [self.tableView insertRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationTop]; [self.tableView endUpdates]; It works great but now I want that the inserted cell be...

Calling dispatch_sync from a concurrent queue - does it block entirely?


ios,objective-c,multithreading,swift,grand-central-dispatch
Let's say I hypothetically call a dispatch_sync from a concurrent queue - does it block the entire queue or just that thread of execution?

Objective-C AVCaptureDevice Front Camera


ios,objective-c,camera,avcapturedevice,avcapture
I have followed a tutorial that guided through a way to make a custom but simple camera app, almost exactly to the needs of the use I would like it. I actually have two issues that I need changing but I will focus on this first one for now. The...

Read plist inside ~/Library/Preferences/


objective-c,xcode,osx
I'm trying to access in ~/Library/Preferences/ but my code doesn't work. NSString *resPath = @"~/Library/Preferences/"; NSError *error = nil; NSArray *filenames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:resPath error:&error]; if (!error) { for (NSString * filename in filenames) { NSLog(@"%@", filename); } } Maybe I should ask for some permission.. Any idea?...

Indent second line of UILabel


ios,objective-c,uilabel
So I have a UILabel that may or may not go to a second line, depending if it is on iPhone or iPad. What I would like to accomplish is to have it indent on the second line to line up correctly, if needed. On iPad it will almost never...

SceneKit + Collada + animation


objective-c,animation,blender,scenekit,collada
I am trying to use Apple's SceneKit in order to load a model from Blender in Collada (dae) format, then apply animation on it from another Collada file, just like Apple did in their Banana example. I can do this with their models and animation files, however, if I open...

Cursor doesn't update in NSTextField as it autoresizes when resizing the enclosing NSWindow


objective-c,cocoa,nstextfield,autoresize,nscursor
I have an NSTextField that autoresizes. Its text is centered. When I start typing in the field and then resize the enclosing NSWindow, the cursor stays where it's at rather than repositioning to the appropriate place : I've also made an XCode project demonstrating this problem : https://www.dropbox.com/sh/cohhmslyl9ti43b/AAC6ULteopsQCMDsEArJU15Ta?dl=0 Does anyone...

Call method after asynchronous request obj-c


ios,objective-c,asynchronous,uiviewcontroller,nsobject
In my app I init a new object, where there is method which calls NSURLConnection's sendAsynchronousRequest method. After the request, I would like to call a method in the caller UIViewController. I tried to use a static method but I then I can't control IBOutlets. How can I do this?...

Height did not update when switch from portrait to Landscape?


ios,objective-c,iphone,landscape-portrait
I create a UIScrollView, added other data in it, added subview to self.view. The problem is that when i switch my phone from portrait to landscape or vice versa it do not update the height so my scrollview do not work as i need to. here is the code: UIScrollView...

Copying Variable Names


objective-c
<code> //header file has appropriate declarations but not included here: #import "AddressCard.h" @implementation AddressCard; -(NSString *) name { return name; } //Recommended code: -(void) setName: (NSString *) theName { [name release] name = [[NSString alloc] initWthString: theName]; } //Incorrect code according to Kochan: -(void) setName: (NSString *) theName { [name...

Slide in an UIButton and push other UIButton when a certain distance is reached


ios,objective-c,uiviewanimation,nslayoutconstraint
I would like to slide in a UIButton (grey color in screenshot) from the left to right and center it on the screen. There is an UIButton (orange color in screenshot) already though that is centered and this button should be pushed to the right and always have a distance...

NSString to NSDate doesn't work


ios,objective-c,nsdateformatter
now it works with this code: NSString *myDate = @"06/18/2015 8:26:17 AM"; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"MM/dd/yyyy hh:mm:ss a"]; [dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US"]]; NSDate *date = [dateFormatter dateFromString:myDate]; [dateFormatter setDateFormat:@"dd.MM. HH:mm"]; NSString *dateString = [dateFormatter stringFromDate:date]; cell.timeLabel.text = dateString; ...

pushviewcontroller doesn't work?


ios,objective-c,pushviewcontroller
There is a button at the viewcontroller and when i click the button pushviewcontroller doesn't work. my appdelegate.m file : - (BOOL)applicationUIApplication *)application **didFinishLaunchingWithOptionsNSDictionary** *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:EK_SCREEN_BOUNDS]; ExampleViewController *exampleViewController = [ExampleViewController new]; self.window.rootViewController = exampleViewController; [self.window makeKeyAndVisible]; return YES; } Button click method (in ExampleViewController): mainViewController...

UIWebView path depends on previous pressed button Xcode


ios,objective-c,iphone,xcode,uiviewcontroller
I have a ViewController (A), containing n buttons. all buttons map to other ViewController(B) containing a WebView to show a different PDF. Instead of creating n ViewController, I would know how to change path according to which button was pressed. my wrong tries: 1- use tags of buttons in ClassB...

How can i use MapKit View in Xcode 6.3?


ios,objective-c,iphone
I am unable to use MapKit in Xcode 6.3. It is showing an error when I am create property for that. The Error is- Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason: 'Could not instantiate class named MKMapView'

CPU & Memory steadily increase & FPS drops all because of vector movement


ios,objective-c,sprite-kit
My CPU & Memory steadily increases over the course of roughly 6 minutes during play testing of my current Sprite Kit game. I've found that the method '-(void)walkToward:(CGPoint)targetPosition' inside the Player class is responsible (it moves the character to a tapped location on screen), but I DON'T understand why. The...

Set color CFAttributedStringRef


ios,objective-c
I have this methods for draw a table ant populated . What i want is to change the color for one word from each column , but i dont know how can i do it . Can somebeday help me ,please ? Any help will be appreciate . in my...

how i can solve Image auto resize in iphone 4 5 6 6+


ios,objective-c,iphone,objective
I give three types of image like image.png [email protected] [email protected] but not working image autoresize in all device....

Obj-C Instance method returning a instanceType called from Swift - Function produces expected type 'UIImage!' error


ios,objective-c,swift
I have this instance method in an existing Obj-C UIImage category: - (UIImage *)applyDarkEffect; I'm trying to call it from a Swift file like so: self.backgroundImageView.image = UIImage.applyDarkEffect(image) But get this compiler error: Function produces expected type 'UIImage!'; did you mean to call it with '()'? ...