Re: UITable Views and display lags
On Mar 19, 2010, at 6:40 PM, Michael Davey wrote: > OK, so I have changed the code to show a placeholder image, but I am a little > uncertain as to how to fetch the images asynchronously. I could start a > background thread with performSelectorInBackground, but am concerned that > this would spawn far too many threads - does anyone have any suggestions? You might want to use an NSOperationQueue. Define NSOperation instances, each fetching one or more images. For each fetching NSOperation you define, you should also define a "cleanup" NSOperation, dependent on its associated fetching one, so that when the fetching one ends, the cleanup one then swaps the placeholder image out and the fetched images in. Make sure, though, that this swap happens in the main thread, meaning that the cleanup NSOperation should invoke a -performSelectorInMainThread method, rather than access the UI directly.___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: UITable Views and display lags
On Mar 21, 2010, at 5:52 PM, Matt Neuburg wrote: > On Fri, 19 Mar 2010 18:55:12 +0100, WT said: >> On Mar 19, 2010, at 6:40 PM, Michael Davey wrote: >> >>> OK, so I have changed the code to show a placeholder image, but I am a >>> little > uncertain as to how to fetch the images asynchronously. I could start a > background thread with performSelectorInBackground, but am concerned that this > would spawn far too many threads - does anyone have any suggestions? >> >> You might want to use an NSOperationQueue. Define NSOperation instances, each > fetching one or more images. For each fetching NSOperation you define, you > should also define a "cleanup" NSOperation, dependent on its associated > fetching > one, so that when the fetching one ends, the cleanup one then swaps the > placeholder image out and the fetched images in. Make sure, though, that this > swap happens in the main thread, meaning that the cleanup NSOperation should > invoke a -performSelectorInMainThread method, rather than access the UI > directly. > > I'm just curious: Why is it better to have a fetching NSOperation and a > cleanup NSOperation dependent on it, rather than a single NSOperation that > fetches and then tells the main thread to show the image? m. Why not rely on NSOperation's built-in dependency mechanism rather than write extra code to find out when loading the image(s) is done? W. ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: UITable Views and display lags
On Mar 21, 2010, at 6:25 PM, Jack Carbaugh wrote: > You don't need to overcomplicate downloading the images with an NSOperation. > > In my experience, downloading asynchronously with an NSURLConnection and the > delegate methods works far better. > > Jack I don't think using NSOperation is overcomplicating things. It's entirely trivial to use it and, as far as I know, NSOperationQueue takes care of scheduling the threads to make the best use of the resources available. W.___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: UITable Views and display lags / NSOperation vs NSURLConnection
It was serial? Did you, by any chance, set the maximum number of running operations to 1? I don't recall for sure now, but that may be the default, actually. As far as I know, independent NSOperations in the same queue are executed in parallel, subjected to resource constraints and the maximum number of running operations. I'm not disputing your results, by the way. As you said, using NSURLConnection might be the best approach in some cases, and perhaps the OP's situation as well. I only suggested NSOperation because that's what I've successfully used a few times, with minimal effort. I'm about to start a project where I have to do precisely what the OP needs to do (fetch and display many images off the web), so I'll try both ways, time permitting. W. On Mar 21, 2010, at 7:06 PM, Jack Carbaugh wrote: > NSURLConnection does this as well. The main issue i had with using an > NSOperation/OperationQueue was that is was "serial" ... using the > NSURLConnection allowed me to handle MULTIPLE asynchronous downloads which, > when used with properties allowed near instantaneous UI updates. > > With the NSOperation avenue, it took longer, UI updates were not as fast as > the queue would handle only one operation at a time, in series. > > For me, the NSURLConnection route was just better for my specific needs and, > i think may be as well for the OP. > > jack > > On Mar 21, 2010, at 1:53 PM, WT wrote: > >> On Mar 21, 2010, at 6:25 PM, Jack Carbaugh wrote: >> >>> You don't need to overcomplicate downloading the images with an NSOperation. >>> >>> In my experience, downloading asynchronously with an NSURLConnection and >>> the delegate methods works far better. >>> >>> Jack >> >> I don't think using NSOperation is overcomplicating things. It's entirely >> trivial to use it and, as far as I know, NSOperationQueue takes care of >> scheduling the threads to make the best use of the resources available. >> >> W.= > ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: iPhone search of my app's data?
You can always slide the search field into the window, below the navigation bar, while pushing (or, perhaps, vertically resizing) the table view. If you set the auto-resizing properties of the table view correctly, more than half of the work is already done. The only remaining question is one of usability: how do you let the user know that search functionality is available? One way is this: when the user scrolls the table view (by swiping vertically downward or by flicking in that direction) and the table view's top row becomes visible, you can slide the search field in as if it was another row. The user will have the impression that it's a single, seamless, action. Scrolling in the opposite direction then slides the search field away. Another way is hidden but, once known, quite effective: when the user taps-and-holds the screen, the search field slides in after a short delay, and stays there until the user dismisses it in the same way, or through actually searching for something. On Mar 21, 2010, at 7:09 PM, William Squires wrote: > Hi all! > Okay, I've mostly finished my (in-house-only) corporate phone-book app; just > needs a few tweaks now. > My app is a navigation-based application with a single UITableView for the > main view, with "Edit" and "+" (add) buttons on the nav-bar on top, so > there's no room to put a search field there. What's the best way to provide > for a search? > > 1) put another button (is it even possible?) on the nav-bar that takes the > user to a "search" view, or > 2) try to make use of the iPhone's built-in search capability somehow? If so, > could someone please email me the link to Apple's on-line docs for this, and > cc it to squire...@yahoo.com, also? ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: UITable Views and display lags / NSOperation vs NSURLConnection
And thank you for the NSURLConnection suggestion. It's always good to have alternatives. :) W. On Mar 21, 2010, at 7:25 PM, Jack Carbaugh wrote: > hmmm to be honest, I am not sure ... there is a possibility that i did NOT > adjust the max # of concurrent operations. > > I will look into this and THANK YOU for the insight. > > > On Mar 21, 2010, at 2:22 PM, WT wrote: > >> It was serial? Did you, by any chance, set the maximum number of running >> operations to 1? I don't recall for sure now, but that may be the default, >> actually. As far as I know, independent NSOperations in the same queue are >> executed in parallel, subjected to resource constraints and the maximum >> number of running operations. >> >> I'm not disputing your results, by the way. As you said, using >> NSURLConnection might be the best approach in some cases, and perhaps the >> OP's situation as well. I only suggested NSOperation because that's what >> I've successfully used a few times, with minimal effort. >> >> I'm about to start a project where I have to do precisely what the OP needs >> to do (fetch and display many images off the web), so I'll try both ways, >> time permitting. >> >> W. >> >> On Mar 21, 2010, at 7:06 PM, Jack Carbaugh wrote: >> >>> NSURLConnection does this as well. The main issue i had with using an >>> NSOperation/OperationQueue was that is was "serial" ... using the >>> NSURLConnection allowed me to handle MULTIPLE asynchronous downloads which, >>> when used with properties allowed near instantaneous UI updates. >>> >>> With the NSOperation avenue, it took longer, UI updates were not as fast as >>> the queue would handle only one operation at a time, in series. >>> >>> For me, the NSURLConnection route was just better for my specific needs >>> and, i think may be as well for the OP. >>> >>> jack >>> >>> On Mar 21, 2010, at 1:53 PM, WT wrote: >>> >>>> On Mar 21, 2010, at 6:25 PM, Jack Carbaugh wrote: >>>> >>>>> You don't need to overcomplicate downloading the images with an >>>>> NSOperation. >>>>> >>>>> In my experience, downloading asynchronously with an NSURLConnection and >>>>> the delegate methods works far better. >>>>> >>>>> Jack >>>> >>>> I don't think using NSOperation is overcomplicating things. It's entirely >>>> trivial to use it and, as far as I know, NSOperationQueue takes care of >>>> scheduling the threads to make the best use of the resources available. >>>> >>>> W.= >>> > ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: UITable Views and display lags / NSOperation vs NSURLConnection
Hmm, now I am confused because I just checked the docs for NSOperationQueue and it says: maxConcurrentOperationCount Returns the maximum number of concurrent operations that the receiver can execute. - (NSInteger)maxConcurrentOperationCount Return Value The maximum number of concurrent operations set explicitly on the receiver using the setMaxConcurrentOperationCount: method. If no value has been explicitly set, this method returns NSOperationQueueDefaultMaxConcurrentOperationCount by default. According to the above, if no value is explicitly set, the getter returns NSOperationQueueDefaultMaxConcurrentOperationCount, which would lead me to believe that that is the default. Yet, according to your experience, the default seems to be 1. So, which one is it? Does anyone in the list know for sure? W. On Mar 21, 2010, at 7:51 PM, Jack Carbaugh wrote: > W > > You were correct, I had not altered the queue to something other than the > default. After reviewing the docs, i found this ... > >> If you specify the value NSOperationQueueDefaultMaxConcurrentOperationCount >> (which is recommended), the maximum number of operations can change >> dynamically based on system conditions. > > > ... which, really, i think should be the default, rather than 1. Since i was > using an NSOperation in another area, i adjusted the queue to the > NSOperationQueueDefaultMaxConcurrentOperationCount value and noticed > significant improvement. > > Again, my thanks ... and yes, it is great to have alternatives. > > jack > > On Mar 21, 2010, at 2:42 PM, WT wrote: > >> And thank you for the NSURLConnection suggestion. It's always good to have >> alternatives. :) >> >> W. >> >> On Mar 21, 2010, at 7:25 PM, Jack Carbaugh wrote: >> >>> hmmm to be honest, I am not sure ... there is a possibility that i did NOT >>> adjust the max # of concurrent operations. >>> >>> I will look into this and THANK YOU for the insight. >>> >>> >>> On Mar 21, 2010, at 2:22 PM, WT wrote: >>> >>>> It was serial? Did you, by any chance, set the maximum number of running >>>> operations to 1? I don't recall for sure now, but that may be the default, >>>> actually. As far as I know, independent NSOperations in the same queue are >>>> executed in parallel, subjected to resource constraints and the maximum >>>> number of running operations. >>>> >>>> I'm not disputing your results, by the way. As you said, using >>>> NSURLConnection might be the best approach in some cases, and perhaps the >>>> OP's situation as well. I only suggested NSOperation because that's what >>>> I've successfully used a few times, with minimal effort. >>>> >>>> I'm about to start a project where I have to do precisely what the OP >>>> needs to do (fetch and display many images off the web), so I'll try both >>>> ways, time permitting. >>>> >>>> W. >>>> >>>> On Mar 21, 2010, at 7:06 PM, Jack Carbaugh wrote: >>>> >>>>> NSURLConnection does this as well. The main issue i had with using an >>>>> NSOperation/OperationQueue was that is was "serial" ... using the >>>>> NSURLConnection allowed me to handle MULTIPLE asynchronous downloads >>>>> which, when used with properties allowed near instantaneous UI updates. >>>>> >>>>> With the NSOperation avenue, it took longer, UI updates were not as fast >>>>> as the queue would handle only one operation at a time, in series. >>>>> >>>>> For me, the NSURLConnection route was just better for my specific needs >>>>> and, i think may be as well for the OP. >>>>> >>>>> jack >>>>> >>>>> On Mar 21, 2010, at 1:53 PM, WT wrote: >>>>> >>>>>> On Mar 21, 2010, at 6:25 PM, Jack Carbaugh wrote: >>>>>> >>>>>>> You don't need to overcomplicate downloading the images with an >>>>>>> NSOperation. >>>>>>> >>>>>>> In my experience, downloading asynchronously with an NSURLConnection >>>>>>> and the delegate methods works far better. >>>>>>> >>>>>>> Jack >>>>>> >>>>>> I don't think using NSOperation is overcomplicating things. It's >>>>>> entirely trivial to use it and, as far as I know, NSOperationQueue takes >>>>>> care of scheduling the threads to make the best use of the resources >>>>>> available. >>>>>> >>>>>> W.= ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: iPhone search of my app's data?
On Mar 22, 2010, at 12:39 AM, Kyle Sluder wrote: > On Sun, Mar 21, 2010 at 11:36 AM, WT wrote: >> You can always slide the search field into the window, below the navigation >> bar, while pushing (or, perhaps, vertically resizing) the table view. If you >> set the auto-resizing properties of the table view correctly, more than half >> of the work is already done. The only remaining question is one of >> usability: how do you let the user know that search functionality is >> available? > > Is there a reason it can't just be another row? The iPod app seems to > behave this way. If you tap the status bar, the search field comes > into view, and it appears as its own entry in the index on the right. > > --Kyle Sluder No, no reason why not. Still, the question of usability remains, ie, how to let the user know that there is search available. W.___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Preservation of State
On Apr 5, 2010, at 6:04 PM, Frederick C. Lee wrote: > Greetings: >I wish to preserve the state of an iPhone/iTouch application; which means > that I would like the application to continue deep down within a stock of > View Controllers at a particular view when I return to the application. > > Does this mean that I need to preserve the ID of a particular > viewController/position in the NSUserDefaults? For example, I store a > unique identifier/pathway of a target in NSUserDefaults then navigate back to > that position upon return to the application? > > > What is the recommended paradigm to handle this? > > Regards, > > Ric Hi Frederick, I've been giving some thought to the same question lately and here's what I've come up with. For a UI that is heavy on drilling down a hierarchy of view controllers, I imagine the path from the application's root view controller to any other view controller as represented by an instance of NSIndexPath. So, for example, the index path 1.3.2 would represent going through the second VC from the root controller, then the fourth VC accessible from that, then the third VC accessible from that. (Recall that indices in an index paths are zero-based) So, one could have an index path ivar in the application delegate which is updated every time a given VC is pushed into, or popped from, the navigation stack. Naturally, that ivar is saved when the application terminates and read when the application starts up. Then, once it's read back in, it's just a matter of following the bread crumbs to the last visited view controller. Of course, one needs to make sure that this "automated" walk-through of the hierarchy has the same relevant effects as when the user did it, but not everything needs to be redone. For instance, animations that might happen in the intermediate view controllers need not be performed again, since the goal is to get back to the last visited view controller as quickly as possible. I'm very interested in other people's take on this issue, since I have no idea if my solution is the best or even the recommended way of achieving the desired result. Wagner___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
How to subclass UIButton?
Hello all, I need to create a custom bar of UIButton instances which can be scrolled left and right using a swipe gesture. I am thus following the "Autoscroll" sample code from Apple, which subclasses UIImageView to produce a scrollable bar of thumbnail images. My problem is how to correctly subclass UIButton, since the only available means of instantiating a button is through the class method +buttonWithType:. Once I allocate an instance of the subclass, how do I initialize it with the desired type? The buttonType property is read-only and there is no instance method -initWithType: in the public API. One alternative I see is to use composition rather than subclassing, essentially creating a decorator for UIButton, but I'd rather not have to do that. Another option is to fake a button using UIImageView, just like the "Autoscroll" example does, but I'd prefer to have actual UIButton instances. Am I missing something trivial here? If UIButton was designed in such a way to prevent subclassing, what would you suggest as the best alternative? Thanks in advance. WT.___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: How to subclass UIButton?
On Apr 8, 2010, at 6:44 AM, john chen wrote: > I think UIButton is not designed for subclassing. That was my hunch as well. > You can try > composition, or create UIButton category method for custom-build > button. Apple has sample code in UICatalog to create custom-build > button. A category on UIButton won't work for me because I need to add extra state to the custom button. The best alternative I've come up with is to have a custom UIView object that contains a UIButton instance and which hijacks touch events by overriding -hitTest:withEvent: to return self. Once the swiping and reordering (as in the Autoscroll sample code) have been dealt with, this "proxy" UIView instance can decide if/when to forward a tap gesture to the button. So, yes, composition seems to be the way to go here. > On Wed, Apr 7, 2010 at 2:26 PM, WT wrote: >> Hello all, >> >> I need to create a custom bar of UIButton instances which can be scrolled >> left and right using a swipe gesture. I am thus following the "Autoscroll" >> sample code from Apple, which subclasses UIImageView to produce a scrollable >> bar of thumbnail images. My problem is how to correctly subclass UIButton, >> since the only available means of instantiating a button is through the >> class method +buttonWithType:. >> >> Once I allocate an instance of the subclass, how do I initialize it with the >> desired type? The buttonType property is read-only and there is no instance >> method -initWithType: in the public API. >> >> One alternative I see is to use composition rather than subclassing, >> essentially creating a decorator for UIButton, but I'd rather not have to do >> that. >> >> Another option is to fake a button using UIImageView, just like the >> "Autoscroll" example does, but I'd prefer to have actual UIButton instances. >> >> Am I missing something trivial here? If UIButton was designed in such a way >> to prevent subclassing, what would you suggest as the best alternative? >> >> Thanks in advance. >> WT. ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: How to subclass UIButton?
> If you want to use the existing buttonWithStyle: method, all you need > to do is implement initWithFrame:, since that's the default > initializer Is the fact that -initWithFrame: is the designated initializer documented anywhere? The docs for UIButton don't mention it. If this is documented and/or won't change, then it's the solution I've been looking for. Thanks! On Apr 8, 2010, at 8:14 AM, Jack Nutting wrote: > I've successfully subclassed UIButton with no problems. I my case I > wasn't interested in the "style" since I was implementing my own, so I > created my own class method which just calls initWithFrame: > > + (id)buttonWithFrame:(CGRect)frame { > return [[[self alloc] initWithFrame:frame] autorelease]; > } > > - (id)initWithFrame:(CGRect)frame { > if (self = [super initWithFrame:frame]) { >// do my additional initialization here > } > return self; > } > > Note that this way the buttonType isn't explicitly set to anything, > which probably means that it's UIButtonTypeCustom. The Docs don't > seem to actually specify that, but since that's the 0 value in the > enum, that's likely what happens (and that seems to be the observable > behavior as well) > > If you want to use the existing buttonWithStyle: method, all you need > to do is implement initWithFrame:, since that's the default > initializer, then call [MyButton buttonWithStyle:whatever] and you're > done! > > If you also want to be able to use your subclass in .xib files, then > you'll also need to implement initWithCoder: (calling the super > implementation) and put your initialization code in there as well. > > -- > // jack > // http://nuthole.com > // http://learncocoa.org ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
need help getting Apple sample code to compile
Hello all, I'm trying to compile the XML Performance sample code for the iPhone, but I have so far been unsuccessful. I followed the instructions on the readme file, namely, to set the HEADER_SEARCH_PATHS build setting to $SDKROOT/usr/include/libxml2. I also tried both recursive and non-recursive (I think it should be recursive, since the directory in question contains another directory, libxml, which then contains the header files, even though the readme instructions say nothing about the recursive option). I've also verified that the library is in fact included in the project. Yet, I keep getting errors such as .../XMLPerformance/XMLPerformance/Classes/LibXMLParser.h:49:0 Libxml/tree.h: No such file or directory in .../XMLPerformance/XMLPerformance/Classes/LibXMLParser.h I searched the archives for prior messages about this sample code but nothing came up. What am I missing? Thanks in advance. WT___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
[iPhone] Frustrated by a simple task
The client I'm writing an app for wants a splash screen with some information that cannot go in the launch image (because it's dynamically generated), meaning that the first view controller to ever be instantiated will have in its view an image view along with other views (labels to hold the generated information). The image view's image must match the launch image, so the overall desired effect is that the app loads (with the launch image being scaled up as usual), then the "startup" view controller is instantiated, its view is shown with a background image that precisely matches the end of the launch-image scaling, and then a second or two later, the app moves on to the actual navigation controller. My problem is matching image and view sizes (specifically, heights) so that the background image does not appear to change from the end of the scaling of the launch image to the showing of the "startup" view controller's view. No matter what I've tried, the client logo in the background image either moves up, or gets stretched up, or both. The labels also sometimes move up (whereas they should be positioned at a fixed distance from the bottom of the screen). The launch image is 320 x 480, as mandated. In my MainWindow.xib, I have an instance of the first view controller to ever be instantiated (the "startup" view controller) and, of course, an instance of its view. That view has an image view as a subview, along with some labels. I've tried several combinations of a) setting the height of the view controller's view to 460 or 480 b) setting the height of the image view to 460 or 480 c) setting the image that goes into that image view to the Default.png image (which is 320 x 480) or setting it to a version of the launch image that is "missing" the top 20 pixels (so it's 320 x 460, coinciding with the the bottom 320 x 460 pixels of Default.png) d) turning on or off the simulated status bar e) setting various options for how the image view is positioned when its frame changes (scale to fill, top, bottom) f) setting the vertical position of the image view to -20, 0, or 20 Clearly, there are far too many combinations to try and the underlying problem is that I don't understand the details of the launch process when it comes to positioning the first view controller's view. So, here's what I would like to ask: either for the correct "recipe" (even without an explanation - I can figure it out once I have the correct setup) or, preferably, for a pointer to a place in the documentation where I can read about the exact process that goes on here. I've searched the documentation but must have missed the mark. This is clearly a very simple task and, yet, it's been frustrating me to no end. Thanks in advance. WT___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: [iPhone] Frustrated by a simple task
On May 13, 2010, at 12:39 AM, Ricky Sharp wrote: > Splash screens should be avoided at all costs in iPhone OS apps. Remember > that you want the app to launch as quickly as possible and let the user > immediately begin doing tasks. Splash screens are typically only useful when > a desktop app needs to pre-load lots of resources. On iPhone OS, you want to > load things lazily. I totally concur, but... > But, if your hand is being forced, then read on... ... my hand is being forced. I've tried to argue some HIGs sense into the client, to no avail. In the end, it's their money, their call, and their fault, if the app doesn't do well in the app store. > It sounds like the app, when running, always displays the status bar. Correct. > All you need to do is load up the original launch image in say Photoshop, > then basically lob off the top 20 rows of pixels. The resultant image will > then be the bottom-most 460 horizontal lines. That was one of the things I tried, but somehow it still doesn't work. Clearly, I've changed some property somewhere that's messing things up. I think I'll try a sample app built afresh and try again, since now I know that just nipping off a 20-pixel-long bar at the top should work. Thanks for the help. WT___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
[iPhone] How to access the Cancel button in a search bar?
The subject pretty much says it all. I need to access the Cancel button of a search bar, so I can change its title. I couldn't find a way to set an outlet to it in IB, and the docs don't show it as a property of the search bar. Any ideas? Thanks in advance. WT___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Adding Mutiple Lines to a UITableView
Hi Nick, you can add more content (labels or any other views) to the contentView of the cell (in the -tableView:cellForRowAtIndexPath: method of the table view data source) or you can create a custom cell. Read the documentation of UITableViewCell and the Table View Programming Guide for details. WT On May 20, 2010, at 1:42 AM, Nick Rawlins wrote: > Hi, > > Does anyone have any suggestions or examples on adding more than 2 lines to > a UITableView row on the iPhone? > > > I am using textLabel and detailTextLabel at present but wish to also add a > 3rd and 4th line. > > > Best Regards, > > Nick ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
[iPhone] Preprocessing events sent to UITableView
I need to hijack the set of touch events sent to a UITableView instance prior to allowing the table to process those events. I have a custom UIView, of which the table view is a subview, and I override -hitTest:withEvent: there (in the custom view) to return self, thereby preventing the table from receiving those touches. Since my custom view does not implement any of the four event-handling methods (-touchesBegan:withEvent:, etc), the view controller managing my custom view gets the touches, through the regular traversal of the responder chain. There, in the view controller event-handling methods, I determine whether or not I need to consume the events. If not, I need to send them back to the table view for it to do its normal event handling (for instance, scrolling). All of the above works fine, except... ... how do I send the touch events back to the table view? I tried storing the actual result of the hit-test (I'm not going to assume it's the table view) in the custom view prior to returning self as the hit-view, then accessing that from the view controller that manages the custom view, and then invoking the four event-handling methods in the actual hit-view from within the corresponding methods in the view controller, but that didn't work. The table view still doesn't get the touches. What's the recommended way of doing what I need to do? Thanks in advance. Wagner___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: [iPhone] Preprocessing events sent to UITableView
On Jun 6, 2010, at 2:09 AM, glenn andreas wrote: > On Saturday, June 05, 2010, at 05:51PM, "WT" wrote: >> I need to hijack the set of touch events sent to a UITableView instance >> prior to allowing the table to process those events. >> >> I have a custom UIView, of which the table view is a subview, and I override >> -hitTest:withEvent: there (in the custom view) to return self, thereby >> preventing the table from receiving those touches. >> >> Since my custom view does not implement any of the four event-handling >> methods (-touchesBegan:withEvent:, etc), the view controller managing my >> custom view gets the touches, through the regular traversal of the responder >> chain. >> >> There, in the view controller event-handling methods, I determine whether or >> not I need to consume the events. If not, I need to send them back to the >> table view for it to do its normal event handling (for instance, scrolling). >> >> All of the above works fine, except... > > > Probably not as "fine" as you expect - UIViews are not designed to support > UIEvents forwarded to them except under very controlled conditions. From > <http://developer.apple.com/iphone/library/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/EventHandling/EventHandling.html#//apple_ref/doc/uid/TP40007072-CH9-SW17>: > > "The classes of the UIKit framework are not designed to receive touches that > are not bound to them; in programmatic terms, this means that the view > property of the UITouch object must hold a reference to the framework object > in order for the touch to be handled. If you want to conditionally forward > touches to other responders in your application, all of these responders > should be instances of your own subclasses of UIView." > > That document contains a number of suggestions on how to approach those sort > of design issues... Yes, I'm aware of that recommendation. I think that's precisely the core of my question, namely, how to do what I need to do in the safest possible way. I found a solution, but I don't think it's very elegant: I subclassed UITableView and, in that subclass, I implement the 4 event methods to call their namesakes in the tableview's superview. Since that superview doesn't implement those methods (it's a regular UIView, not a custom view), its view controller gets the calls (through the normal traversal of the responder chain). There I do the analysis to decide whether or not to consume the touches. If not, then I call "fake" event methods in the tableview's subclass, each of which invokes the super version of the true event methods. It works like a charm, but it's not very elegant, in my opinion.___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: [iPhone] Preprocessing events sent to UITableView
Fair enough. The app I'm writing is a newspaper-like app, similar to The New York Times app. The client for whom I'm writing this app wants the reader to be able to swipe horizontally to switch sections (say, from "latest news" to "sports" to "entertainment", etc). Each section has its own view controller, all of which manage a shared view. That view is part of a larger view which contains, among other things, a scrollable list of section "buttons." That larger view, of course, has its own view controller. The reader can tap on a section button and the contents of that section get dumped into the tableview but the client also wants the user to be able to swipe horizontally to switch sections. Naturally, the view controller for a section is not the appropriate place to manage the swipe since it involves knowledge about other sections. So, I need to intercept the touch events received by the table view, pass them a couple of levels up to the view controller of the larger view, do the analysis to figure out whether to swipe or allow the table to scroll, then pass the events back down to the table if the user intended to scroll vertically. The solution I indicated works fine, but I don't think it's very elegant. Personally, I think swiping to change sections is a bad idea, but that's not my call to make. On Jun 6, 2010, at 4:30 PM, David Duncan wrote: > On Jun 6, 2010, at 1:41 AM, WT wrote: > >> Yes, I'm aware of that recommendation. I think that's precisely the core of >> my question, namely, how to do what I need to do in the safest possible way. > > > I think you need to tell us what the goal you are trying to achieve is, > rather than asking how to do it the way you think you should. Then perhaps > someone can recommend a better solution. > -- > David Duncan > Apple DTS Animation and Printing On Jun 6, 2010, at 4:37 PM, Matt Neuburg wrote: > On Sun, 6 Jun 2010 10:41:41 +0200, WT said: > >> question, namely, how to do what I need to do in the safest possible way. I > found a solution, but I don't think it's very elegant > > Sorry if I'm being dense, but did we establish what you *do* need to do? I > didn't grasp why you're jumping through all these hoops in the first place. > Just curious... Thx. m. ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
[iPhone] Determining minimum height for a UIWebView
Hello, I'm trying to find out how to set the height of a UIWebView instance, given its content, so that the user doesn't need to scroll the UIWebView itself to see that content. Of course, the content might not fit in the vertical space available but the UIWebView instance is part of a tableview cell, so scrolling will be handled by the table view. Any help is greatly appreciated. WT___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: iPhone puzzle about rotation
On Jan 31, 2011, at 11:16 PM, David Rowland wrote: > Is there something that defeats the delivery of rotate events to a view > controller? This may or may not be the case with your app, but a UITabBarController vetoes device orientation change events to its managed view controllers unless every one of them supports the orientation change in question. However, it still calls the view controllers' -shouldAutorotateToInterfaceOrientation: method (as it must, in order to find out if they all support the orientation change being requested). It may not invoke them every time, though. Rather, it may invoke them once per view controller and cache the result. I don't know which is the case, but it's easy to check.___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
[iOS] Strange behavior of NSFetchedResultsController
Hello list, I'm experiencing a strange behavior on the part of NSFetchedResultsController and I can't seem to find why, although I suspect it's something utterly simple that I'm just not seeing. Here's the setup. I have a list of some 20 keys the user can choose from to sort some experimental data by, and these keys are represented in a core data model. The custom subclass of NSManagedObject that encapsulates each key is called SortDescriptorCD and is defined as follows (other non-relevant stuff has been removed): // SortDescriptorCD.h #import // class statements @interface SortDescriptorCD: NSManagedObject {} @property (readwrite, nonatomic, retain) NSNumber* index; @property (readwrite, nonatomic, retain) NSString* title; @property (readonly, nonatomic, retain) id indexOrTitle; @property (readwrite, nonatomic, retain) NSNumber*canAppearOnList; @property (readwrite, nonatomic, retain) NSNumber* doesAppearOnList; @property (readonly, nonatomic, retain) NSNumber* canAndDoesAppearOnList; // other property declarations @end // SortDescriptorCD.m #import "SortDescriptorCD.h" // other import statements @implementation SortDescriptorCD @dynamic index; @dynamic title; @dynamic canAppearOnList; @dynamic doesAppearOnList; // other dynamic declarations - (id) indexOrTitle; { if ([self.canAndDoesAppearOnList isEqualToNumber: [NSNumber numberWithBool: YES]]) { return self.index; } else { return self.title; } } - (NSNumber*) canAndDoesAppearOnList; { BOOL can = [self.canAppearOnList boolValue]; BOOL does = [self.doesAppearOnList boolValue]; return [NSNumber numberWithBool: (can && does)]; } @end Title isn't the actual key, but a human-readable version of it. These keys are sometimes not applicable to the data being shown, hence the canAppearOnList boolean. If they can, then whether or not they actually do is user-defined and that choice is stored in doesAppearOnList. The terminology may seem a bit confusing because there are other things not being shown here. For instance, there is another pair of attributes, canSort and doesSort. The idea is that for those keys that canAppearOnList the user can select whether or not they want to see the information they represent (doesAppearOnList) and, additionally, whether that information is sorted or not (doesSort), assuming that it can be (canSort). And if it can be sorted and if the user chooses to sort by that key, whether it's sorted ascending or descending. When the user de-selects a sorting key, its title gets grayed-out and its cell gets moved to a separate part of the tableview where it appears (it's not a separate tableview section, though I'm considering doing it that way). The selected part is sorted by index to allow the user to re-arrange the sorting order of the selected keys. The non-selected part is sorted by title. Tapping a row in one part moves its cell to the other part. Now, the two attributes indexOrTitle and canAndDoesAppearOnList are defined in the core data model as transformable (optional and using the default transformer). The NSFetchedResultsController is defined as follows: - (NSFetchedResultsController*) sortDescriptorCDs; { NSManagedObjectContext* context = self.managedObjectContext; NSEntityDescription* entity = [NSEntityDescription entityForName: @"SortDescriptorCD" inManagedObjectContext: context]; NSSortDescriptor* sortByCanAndDoesAppearOnList = [[NSSortDescriptor alloc] initWithKey: @"canAndDoesAppearOnList" ascending: NO]; // Replacing @"indexOrTitle" with @"index" or @"title" works fine. NSSortDescriptor* sortByIndexOrTitle = [[NSSortDescriptor alloc] initWithKey: @"indexOrTitle" ascending: YES]; NSArray* sortDescriptors = [[NSArray alloc] initWithObjects: sortByCanAndDoesAppearOnList, sortByIndexOrTitle, nil]; [sortByCanAndDoesAppearOnList release]; [sortByIndexOrTitle release]; NSFetchRequest* fetchRequest = [[NSFetchRequest alloc] init]; [fetchRequest setEntity: entity]; [fetchRequest setSortDescriptors: sortDescriptors]; [fetchRequest setFetchBatchSize: 20]; [sortDescriptors release]; NSFetchedResultsController* frc = [[NSFetchedResultsController alloc] initWithFetchRequest: fetchRequest managedObjectContext: context sectionNameKeyPath: nil cacheName: nil]; [fetchRequest release]; NSError* error = nil; if (! [frc performFetch: &error]) { // TODO - Handle fetching error. NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } return [frc autorelease]; } Note the comment // Replacing @"indexOrTitle" with @"index" or @"title" works fine. which makes me confident that sortDescriptorCDs is implemented correctly. By working fine I mean that the tableview does display al
[iOS] Strange behavior of NSFetchedResultsController
Hello list, a little while ago I posted a question regarding some strange behavior by an NSFetchedResultsController (under the same subject line as this message). Since then I've narrowed the problem down a bit more and now have a test project to show it. Here's what the goal is, in a nutshell. I have a list of, say, countries. Some are "selected", others not. I need to display all the countries in the same tableview, in the same section, and what differentiates the selected ones from the deselected ones is their text color. Moreover, the selected ones should be sorted ascending by their "index" (an integer that's used to keep track of their position in the list) while the deselected ones must be sorted ascending by their "name". The test project's core data model has a single entity, "CountryCD", with the attributes "name", "index", "selected" (representing a boolean), and a transformable attribute "indexOrName" which returns the entity's index if it's selected or its name if it's deselected. - (id) indexOrName; { if ([self.selected isEqualToNumber: [NSNumber numberWithBool: YES]]) { return self.index; } else { return self.name; } } The fetched results controller is defined as usual but contains two sort descriptors: NSSortDescriptor* sortBySelected = [[NSSortDescriptor alloc] initWithKey: @"selected" ascending: NO]; NSSortDescriptor* sortByIndexOrName = [[NSSortDescriptor alloc] initWithKey: @"indexOrName" ascending: YES]; the idea being that entities get sorted first by their "selected" status and then by their "indexOrName" attribute. Since that attribute returns the entity's "index" or its "name", depending on the entity's "selected" status, the fetched results controller *should* sort the entities as desired. Should, but doesn't. And that's the problem I can't seem to solve. In the test project, I create country entities in the following order [self createCountryOfName: @"India"]; [self createCountryOfName: @"Honduras"]; [self createCountryOfName: @"Germany"]; [self createCountryOfName: @"Denmark"]; [self createCountryOfName: @"Brazil"]; [self createCountryOfName: @"Egypt"]; [self createCountryOfName: @"Australia"]; [self createCountryOfName: @"China"]; [self createCountryOfName: @"Finland"]; and make every second one deselected, which *should* result in them being displayed as follows: // (ordered by index) // India // Germany // Brazil // Australia // Finland // (ordered by name) // China // Denmark // Egypt // Honduras Alas, they're displayed like this (or some other seemingly random order): (selected) Brazil Germany Australia India Finland (deselected) Honduras Denmark Egypt China Neither the selected ones are sorted by their "index" attribute nor the deselected ones are sorted by their "name" attribute. In fact, the test project shows that "indexOrName" is not accessed at all when the fetched results controller does its fetch. First I thought that there might be something wrong with the way I implemented the fetched results controller, but if you replace "indexOrName" in the sort descriptor with either "index" or "name", it works as would be expected. So then I thought that using a transformable attribute is not the way to go in order to achieve the result I need to achieve, but I can't see any other way to do it. If using a transformable attribute isn't the way to go, can anyone suggest an alternative? If using a transformable attribute should work, then why doesn't it as I've implemented it? It appears to me that NSFetchedResultsController ignores a sort descriptor based on a transformable attribute. The test project can be found here: http://www.restlessbrain.com/FRC_Test.zip I'd greatly appreciate any help. I've already spent several days trying to figure this out but got nowhere and ran out of ideas. Thanks in advance. WT ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: [iOS] Strange behavior of NSFetchedResultsController
The example of countries is just that, an example. The actual app is about something else. Also, the color of the text is not a model property - the selected status is. I think you didn't quite understand what the problem I'm having is. The problem is that NSFetchedResultsController is ignoring a transformable attribute used as a sorting key. On Feb 10, 2011, at 2:10 PM, claw wrote: > hi, > > i want you to propose just an idea , a remark, on apple documentation is > said > > The NSFetchRequest class is used to describe search criteria used to retrieve > data from a persistent store. implicitely you must record all of them and > update them sometimes > > in your idea there is a lot of different kind of countries ( india, honduras > ) which can have a common property: a selected color that can vary a lot > of times > > why not trying to use an Hash Table in order to use weak reference with > NSHashTable ??instead of each time ask core data to update all the entire > store > > best regards > > > > > Le 10 fรฉvr. 2011 ร 16:19, WT a รฉcrit : > >> Hello list, >> >> a little while ago I posted a question regarding some strange behavior by an >> NSFetchedResultsController (under the same subject line as this message). >> Since then I've narrowed the problem down a bit more and now have a test >> project to show it. >> >> Here's what the goal is, in a nutshell. >> >> I have a list of, say, countries. Some are "selected", others not. I need to >> display all the countries in the same tableview, in the same section, and >> what differentiates the selected ones from the deselected ones is their text >> color. Moreover, the selected ones should be sorted ascending by their >> "index" (an integer that's used to keep track of their position in the list) >> while the deselected ones must be sorted ascending by their "name". >> >> The test project's core data model has a single entity, "CountryCD", with >> the attributes "name", "index", "selected" (representing a boolean), and a >> transformable attribute "indexOrName" which returns the entity's index if >> it's selected or its name if it's deselected. >> >> - (id) indexOrName; >> { >> if ([self.selected isEqualToNumber: [NSNumber numberWithBool: YES]]) >> { >> return self.index; >> } >> else >> { >> return self.name; >> } >> } >> >> The fetched results controller is defined as usual but contains two sort >> descriptors: >> >> NSSortDescriptor* sortBySelected = [[NSSortDescriptor alloc] >> initWithKey: @"selected" ascending: NO]; >> >> NSSortDescriptor* sortByIndexOrName = [[NSSortDescriptor alloc] >> initWithKey: @"indexOrName" ascending: YES]; >> >> the idea being that entities get sorted first by their "selected" status and >> then by their "indexOrName" attribute. Since that attribute returns the >> entity's "index" or its "name", depending on the entity's "selected" status, >> the fetched results controller *should* sort the entities as desired. >> >> Should, but doesn't. And that's the problem I can't seem to solve. >> >> In the test project, I create country entities in the following order >> >> [self createCountryOfName: @"India"]; >> [self createCountryOfName: @"Honduras"]; >> [self createCountryOfName: @"Germany"]; >> [self createCountryOfName: @"Denmark"]; >> [self createCountryOfName: @"Brazil"]; >> [self createCountryOfName: @"Egypt"]; >> [self createCountryOfName: @"Australia"]; >> [self createCountryOfName: @"China"]; >> [self createCountryOfName: @"Finland"]; >> >> and make every second one deselected, which *should* result in them being >> displayed as follows: >> >> // (ordered by index) >> // India >> // Germany >> // Brazil >> // Australia >> // Finland >> >> // (ordered by name) >> // China >> // Denmark >> // Egypt >> // Honduras >> >> Alas, they're displayed like this (or some other seemingly random order): >> >> (selected) >> Brazil >> Germany >> Australia >> India >> Finland >> >> (deselected) >> Honduras >> Denmark >> Egypt &
Re: [iOS] Strange behavior of NSFetchedResultsController
On Feb 10, 2011, at 3:54 PM, Quincey Morris wrote: > Perhaps you're assuming that Core Data will internally call the above getter > to figure out what to put into the store. It doesn't work that way. Most > likely your store contains nil values for the "indexOrName" attribute. (I'm > assuming your Core Data model actually has an "indexOrName" attribute. If > not, it still won't work, but for a different reason.) Yes, that's what I assumed. Yes, the Core Data model does have an "indexOrName" attribute (defined as transformable). No, the values for "indexOrName" stored in the store aren't nil. In fact, here's actual output from the test project: 2011-02-10 16:03:17.083 FRC_Test[13683:207] (entity: CountryCD; id: 0x6105ee0 ; data: { index = 0; indexOrName = "(...not nil..)"; name = India; selected = 1; }) This output happens long before the fetched results controller is created, by the way. I assumed that CD internally calls the getter because it actually has happened, although it isn't entirely clear to me under what circumstances. It appears that once an entity has some attribute changed that affects the fetched results controller, then the next fetch operation does sort the entities as I intended, ie, by invoking the getter for "indexOrName". I thought that this might be due to the fact that the first fetch happens before I assign the FRC's delegate but that isn't the case (I tested this by doing the obvious: fetching after setting the delegate). Also, how is it that "indexOrName" has non-nil values without the getter being called? I suspect that CD stores some empty NSData object for each "indexOrName" entry (since it's defined as an optional transformable attribute) but doesn't call the getter. > The thing you're sorting is a fetched results controller. Presumably that > sorts itself based on the fetched attribute values (all nil for "indexOrName" > in this case), which means that all objects have the same value for the > attribute, so the result of sorting is essentially random, as you've seen. That would make perfect sense if it wasn't for the fact that the stored values for "indexOrName" aren't nil. > You either need to get the actual values of "indexOrName" into the store, or > you need to do your own sorting after the objects have been fetched. I think the former is already the case, hence my surprise that the sorting isn't happening as expected. At this point, I don't know how to debug this any further since the internal workings of NSFetchedResultsController aren't accessible to us (to me, at least). In the absence of figuring out why this isn't working, let me put it differently: how can I create an NSFetchedResultsController that sorts based on multiple keys, at least one of which is a derived attribute? I'll be surprised if this isn't a common task. Thanks for your help. WT___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: [iOS] Strange behavior of NSFetchedResultsController
Your statement that I need to get the values of "indexOrName" stored in the store led me to write the odd-looking line of code below cdCountry.indexOrName = cdCountry.indexOrName; when the entities are created and it fixes the problem in the test project. I'm now more convinced than ever that CD stored an empty NSData object for each "indexOrName" entry, which would explain why their values weren't nil and, yet, they sorted "randomly." Now on to the actual project. Hopefully this is all that is needed. Thanks again for your message. WT___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: [iOS] Strange behavior of NSFetchedResultsController
(Apologies if this message reaches you in duplicate. The first time I sent it, it was flagged as 10 KB too large.) I spoke too soon... Forcing -indexOrName to be invoked at entity creation time ensures that the corresponding attribute has the correct value but the fetched results controller sorts the list as follows: First descending by "selected" (as desired) Then, within the selected group, ascending by "index" (as desired) But, within the deselected group, it sorts them incorrectly by "name". (see picture) Note how Egypt appears before Denmark and Morocco before Honduras. The numbers within parentheses are the entities' "index" values. I've verified that -indexOrName returns the correct value for each entity (which means the values stored in the store for that attribute should be correct), and replacing "indexOrName" with "name" in the second sort descriptor defined for the fetched results controller sorts the names correctly. So, why doesn't it sort them correctly when it's accessing the "indexOrName" stored value? At first I thought that this might be due to using Cocoa sort descriptors with an SQLite store, as explained in http://developer.apple.com/library/ios/documentation/cocoa/conceptual/CoreData/Articles/cdTroubleshooting.html#//apple_ref/doc/uid/TP40002320-SW16 === SQLite store does not work with sorting Problem: You create a sort descriptor that uses a comparison method defined by NSString, such as the following: NSSortDescriptor *mySortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"lastName" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)]; You then either use this descriptor with a fetch request or as one of an array controller's sort descriptors. At runtime, you might see an error message that looks similar to the following: NSRunLoop ignoring exception 'unsupported NSSortDescriptor selector: localizedCaseInsensitiveCompare:' that raised during posting of delayed perform with target 3e2e42 and selector 'invokeWithTarget:' === However, I'm not using a "custom" comparison method and I don't get any runtime error messages. In fact, I'm using the same sort descriptor as in the example found in http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreData/Articles/cdFetching.html#//apple_ref/doc/uid/TP40002484-SW3 namely NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"firstName" ascending:YES]; except that "firstName" is replaced by a derived property (defined as a transformable attribute), "indexOrName", which does produce a string for the entities in the deselected group. Incidentally, the documentation is VERY confusing in this regard since in the blob above it suggests that -localizedCaseInsensitiveCompare: is not supported and could/would cause an exception to be raised while in http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreData/Articles/cdPersistentStores.html#//apple_ref/doc/uid/TP40002875-SW11 it says "The supported sort selectors are compare: and caseInsensitiveCompare:, localizedCompare:,localizedCaseInsensitiveCompare:, and localizedStandardCompare: (the latter is Finder-like sorting, and what most people should use most of the time)." I am extremely frustrated by all this. I've already spent the better part of a week trying to figure this one problem, creating an NSFetchedResultsController that sorts using multiple keys, at least one of which is defined by a derived property, which I would think is a common task, and I'm not making much progress. I most definitely could use someone's help here. I've done all the doc-reading, I've done all the code-walking and debugging, and I've narrowed the problem down to a very specific issue, but I'm still not seeing the light. The most recent test project can be found here: http://www.restlessbrain.com/FRC_Test_2.zip I'd be grateful if someone could look at that project and help me figure out what I'm doing wrong. Thanks in advance. WT <> > Your statement that I need to get the values of "indexOrName" stored in the > store led me to write the odd-looking line of code below > > cdCountry.indexOrName = cdCountry.indexOrName; > > when the entities are created and it fixes the problem in the test project. > I'm now more convinced than ever that CD stored an empty NSData object for > each "indexOrName" entry, which would explain why their values weren't nil > and, yet, they sorted "randomly." > > Now on to the actual project. Hopefully this is all that is needed. > > Thanks again for your message. > WT __
Re: [iOS] Strange behavior of NSFetchedResultsController
On Feb 10, 2011, at 7:28 PM, Quincey Morris wrote: > On Feb 10, 2011, at 12:59, WT wrote: > >> So, why doesn't it sort them correctly when it's accessing the "indexOrName" >> stored value? > > You *cannot* have an attribute that's both a derived property and a stored > property at the same time. The two things are mutually contradictory. Good point. I feel silly now, because that's something I should have realized on my own. > What you've actually done is create two different properties, one derived and > one stored, with the same name, which ends up breaking Core Data in the ways > you're seeing. Yes, I see that now. > You need to choose one. > > If you choose the derived property, then you should get rid of the property > from your Core Data model. (So it's defined in your managed object subclass, > but Core Data knows nothing about it.) In that case, I suspect, you'll get an > error message if you try to use the property name in your fetch results > controller's sort keys. I haven't tried/checked but I'm pretty sure you're right that I won't be able to use the derived property as a sorting key in the fetched results controller. > If you choose the stored property, then you should get rid of your > 'indexOrName' getter, and instead customize the setters for your "index" and > "name" properties to maintain the "indexOrName" property directly. Yes, I think this is the path I'll follow. > Choose one. > > For either choice, though, you also need to pay attention the the KVO > compliance of your "indexOrName" property. If you choose option #1, you'll > likely use keyPathsForValuesAffectingIndexOrName to make that property > properly dependent on changes to the values of the underlying properties. If > you choose option #2, your custom setters must generate KVO notifications > (use setIndexOrName: or will/didChangeValueForKey:) whenever it changes the > stored value. Ah, more documentation to read then... I'm not comfortable with KVO just yet, so this is a good opportunity to learn more. I just wish I hadn't already spent so much time on this one issue. > Welcome to the world of Core Data. :) Heh.. yeah, tricky world it is sometimes. Thanks for all your help. WT ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: IBOutlet to different classes, conditional build
You can define a common superclass for both MyAppDelegate and MyPrefDelegate - MyCommonAppDelegate - and use that as the type of the IBOutlet. You can then #define convenience delegates for each actual case, so you'd have something like: IBOutlet MyCommonAppDelegate* commonDelegate; and then #ifdef RETAIL #define delegate ((MyPrefPaneDelegate*) commonDelegate) #endif #ifdef APPSTORE #define delegate ((MyAppDelegate*) commonDelegate) #endif Your superclass can even have the common code or it could be just an empty "marker" to give both concrete classes a common type. Either way, everywhere else you may continue to use delegate and never have to use commonDelegate. Its only appearance would be where the above appears and in the nibs. And if you can't conveniently define a common superclass for both, define an empty protocol that they both implement, then use that to define the IBOutlet instead. The point is, all you need is a common type for both classes. On Feb 23, 2011, at 4:07 PM, Trygve Inda wrote: > I have one project that outputs two binaries - one for the App Store (an > app) and one for my own website version (a prefpane). > > All the classes are the same except for two: > > MyPrefPaneDelegate > > MyAppDelegate > > These are each in their respective apps. > > How can I build my shared classes so I can do: > > #ifdef RETAIL > IBOutlet MyPrefPaneDelegate delegate > #endif > > #ifdef APPSTORE > IBOutlet MyAppDelegatedelegate > #endif > > > It obviously compiles ok. But I have two nibs... One for the AppStore and > one for the Retail version. My CommonClass is instantiated in both nibs, but > in one case I need an outlet to point to a MyPrefPaneDelegate and in the > other it needs to point to a MyAppDelegate > > Ideas? > > Thanks. > > > ___ > > Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) > > Please do not post admin requests or moderator comments to the list. > Contact the moderators at cocoa-dev-admins(at)lists.apple.com > > Help/Unsubscribe/Update your Subscription: > http://lists.apple.com/mailman/options/cocoa-dev/jrcapab%40gmail.com > > This email sent to jrca...@gmail.com ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: IBOutlet to different classes, conditional build
>>> I have one project that outputs two binaries - one for the App Store (an >>> app) and one for my own website version (a prefpane). >>> >>> All the classes are the same except for two: >>> >>> MyPrefPaneDelegate >>> >>> MyAppDelegate >>> >>> These are each in their respective apps. >>> >>> How can I build my shared classes so I can do: >>> >>> #ifdef RETAIL >>> IBOutlet MyPrefPaneDelegate delegate >>> #endif >>> >>> #ifdef APPSTORE >>> IBOutlet MyAppDelegatedelegate >>> #endif >>> >>> >>> It obviously compiles ok. But I have two nibs... One for the AppStore and >>> one for the Retail version. My CommonClass is instantiated in both nibs, but >>> in one case I need an outlet to point to a MyPrefPaneDelegate and in the >>> other it needs to point to a MyAppDelegate > >> You can define a common superclass for both MyAppDelegate and MyPrefDelegate >> - >> MyCommonAppDelegate - and use that as the type of the IBOutlet. You can then >> #define convenience delegates for each actual case, so you'd have something >> like: >> >> IBOutlet MyCommonAppDelegate* commonDelegate; >> >> and then >> >> #ifdef RETAIL >> #define delegate ((MyPrefPaneDelegate*) commonDelegate) >> #endif >> >> #ifdef APPSTORE >> #define delegate ((MyAppDelegate*) commonDelegate) >> #endif >> >> Your superclass can even have the common code or it could be just an empty >> "marker" to give both concrete classes a common type. Either way, everywhere >> else you may continue to use delegate and never have to use commonDelegate. >> Its only appearance would be where the above appears and in the nibs. >> >> And if you can't conveniently define a common superclass for both, define an >> empty protocol that they both implement, then use that to define the IBOutlet >> instead. >> >> The point is, all you need is a common type for both classes. >> > I guess the other issue is that if I do it this way the retail version needs > to have IBAction methods for Sparkle updating which I need to keep out of > the AppStore version... So how can I set it up so that one nib can have a > button linked to an IBAction (which is part of the delegate class), while > the other nib has a mostly identical nib that does not have these > outlet/actions? > > So when I define MyCommonAppDelegate in the nib, it should only have the > "SparkleUpdate" IBAction in the retail version... So this code really sits > in MyPrefPaneDelegate... But how do I get IB to realize this? > > I am really trying not to have any duplicated code here. Easy. If you use the superclass idea, have the action methods declared and defined in the superclass, with empty implementations. The concrete retail subclass overrides those implementations with what you're actually supposed to do. The concrete app subclass doesn't care. The retail nib has buttons that trigger those actions, the app nib doesn't use the actions at all. If you go with the protocol idea, it's pretty much the same. Define your action methods in the protocol, with empty implementations in the app delegate class and actual useful implementations in the retail delegate class. Again, the retail nib has buttons that trigger those actions, but the app nib ignores them. ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Unique strings array
Hi Leonardo, the easiest and, probably, most efficient way is to insert your words into a (mathematical) set, which guarantees uniqueness. My suggestion then is that you read the documentation on NSSet. You insert all your words into an instance of NSMutableSet and that's it. WT On Mar 11, 2011, at 11:11 PM, Leonardo wrote: > Hi, > I have to extract a list of "unique words" from an array of hundred > thousands words and put them into an uniqueWordsArray. I already succeeded > but the task is very very slow because I don't index the uniqueWordsArray. > So my question is: how to index the array and get a fast check? > Actually I do: > > for(NSString *aWord in wordsArray){ > if([uniqueWordsArray containsObject:aWord] == NO){ >[uniqueWordsArray addObject:aWord]; >} > } > > You understand well that the task works fast at the beginning, but it gets > slower and slower at any word added to the uniqueWordsArray. > What's the best way to do that? > Should I use the internal SQLLite database? CoreData? Other? > > > Regards > -- Leonardo > > > ___ > > Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) > > Please do not post admin requests or moderator comments to the list. > Contact the moderators at cocoa-dev-admins(at)lists.apple.com > > Help/Unsubscribe/Update your Subscription: > http://lists.apple.com/mailman/options/cocoa-dev/jrcapab%40gmail.com > > This email sent to jrca...@gmail.com ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
[iOS] How to animate the height of a UITableViewCell
Hello, in one of my projects, a UITableView instance displays a number of objects whose information is gathered from the web. As it turns out each of these objects can be in one of two states, with visual differences. In the "loading" state, only a minimal amount of information about the object (its "name" and a spinning UIActivityIndicatorView) is displayed, whereas in the "loaded" state (after the web access has been completed and information parsed) a more detailed amount of information is shown. When the object displayed in a given UITableViewCell is in the loading state, the cell's height is just a bit larger than a UILabel's height. When the object is in its "loaded" state, the cell is quite a bit taller, to accommodate the rest of the information. I already have all of this working just fine (including the fact that each cell's object updates its content asynchronously), but the transition from short cell to tall cell is abrupt and I would like to make it be a smooth animation. Can someone please offer some pointers on how to accomplish that? Thanks in advance. WT___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
[Solved] [iOS] How to animate the height of a UITableViewCell
Duh... I should have searched the web before firing the question to the list. It turns out there are many references to this exact task and its solution. Here's one such: http://www.alexandre-gomes.com/?p=482 Basically, the idea is to call -reloadRowsAtIndexPaths: withRowAnimation: at the appropriate moment. Apologies for the unnecessary noise. WT___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: [iOS] How to animate the height of a UITableViewCell
On Mar 14, 2011, at 2:27 PM, Conrad Shultz wrote: > WT wrote: >> When the object displayed in a given UITableViewCell is in the >> loading state, the cell's height is just a bit larger than a >> UILabel's height. When the object is in its "loaded" state, the cell >> is quite a bit taller, to accommodate the rest of the information. >> >> I already have all of this working just fine (including the fact that >> each cell's object updates its content asynchronously), but the >> transition from short cell to tall cell is abrupt and I would like to >> make it be a smooth animation. >> >> Can someone please offer some pointers on how to accomplish that? > > I have found that using: > > - - (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths > withRowAnimation:(UITableViewRowAnimation)animation > > works well, especially when used with UITableViewRowAnimationTop as the > row animation. Hi Conrad, thanks for your reply. As I posted subsequently to my original message, I found that very answer you recommended in several places online, but some of them suggest bracketing the call to -reloadRowsAtIndexPaths:withRowAnimation: with calls to -beginUpdates and -endUpdates, while others don't. Is this bracketing necessary? Thanks again. WT___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: [iOS] How to animate the height of a UITableViewCell
On Mar 14, 2011, at 5:40 PM, Conrad Shultz wrote: > No problem, happy to help, even if you independently found the solution. > > As for begin/endUpdates, what these do is synchronize animations that > otherwise might be performed serially. If you are updating a single row > there is no reason, AFAIK, to wrap the reload message. > > If you are updating multiple rows (which I don't do, so this is somewhat > speculative... a test program should be pretty easy to write), wrapping > the reload message with begin/endUpdates will ensure that all the rows > animate simultaneously. > > What I am unsure on is whether you need to do this if you include all > the row changes in the NSArray you pass to reloadRowsAtIndexPaths. > Cocoa might take care of synchronizing all animations therein for you, > but I'm not sure. Sounds like a good exercise to write a test app to try it. I'll try and explore that issue when I find a bit more time. Meanwhile, I'll just do what I need without the beginUpdates/endUpdates calls since I, too, only need to animate one row at a time. > Certainly if you need to perform other operations > (e.g. adding/deleting cells) you will need to wrap the whole block as > indicated in the documentation. > > A thorough discussion of these matters is available in the Table View > Programming Guide for iOS: > > http://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/TableView_iPhone/ManageInsertDeleteRow/ManageInsertDeleteRow.html#//apple_ref/doc/uid/TP40007451-CH10-SW9 Yes, I've read the table view docs but I'll admit that the last time I did it was some time ago and now I was pressed for time so I skipped the docs at this time. Not a good excuse, I know. :) Thanks again for your help. WT___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Splitting a single Core Data model between several files
Hello, in searching the web and the archives for help on splitting a single CD model into several files, I found that the most recent exchanges on this subject date back to July 2009 and September 2008: Core Data, migrate a model split into two files http://www.cocoabuilder.com/archive/cocoa/240263-core-data-migrate-model-split-into-two-files.html Let's merge managed object models! http://chanson.livejournal.com/187540.html My question is not how to do it (Chris' article above explains how) but whether anything has changed since, in regards to official support in XCode for merging separate model files. Note that this is not specifically about migration but merely about breaking down a complex model into more manageable parts. Is the technique suggested by Chris still the way to go? Should I have posted this in the XCode list instead? Thanks. WT___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: iPhone animation puzzle
I seem to recall that one of the WWDC 2010 instructional videos - available for free from Apple's developer site - mentions that the block version has UIViewAnimationOptionAllowUserInteraction off by default. That being said, have you filed a document enhancement request? WT On Mar 20, 2011, at 1:59 PM, David Rowland wrote: > That did it. > > The "View Programmming Guide for iOS", discusses both methods and implies > that their code samples are equivalent. They don't say, or I didn't see, that > the option you mention is on by default for the begin/commit style and off > for the newer block style. > > thanks, > > David > > > > On Mar 19, 2011, at 5:08 PM, Roland King wrote: > >> UIViewAnimationOptionAllowUserInteraction ? >> >> >> >> On Mar 20, 2011, at 5:42, David Rowland wrote: >> >>> This works. It fades the label to invisibility. >>> >>> label.alpha = 1.0; >>> [UIView beginAnimations:nil context:nil]; >>> [UIView setAnimationDuration:2.5]; >>> label.alpha = 0; >>> [UIView commitAnimations]; >>> >>> >>> and so does this, >>> >>> label.alpha = 1.0; >>> [UIView animateWithDuration:2.5 animations:^{label.alpha = 0.0;} ]; >>> >>> >>> The documentation says the latter is now preferred and does the same thing >>> as the former. In particular, both will >>> start a separate thread for the animation. >>> >>> My problem is that the second method seems to block the main thread. While >>> it is acting I cannot use any of the controls on the screen. The first >>> method lets me do what I wish as it proceeds. >>> >>> >>> Anyone have advice? >>> >>> thanks, >>> >>> David ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Exporting and Importing CoreData
On Mar 23, 2011, at 8:13 PM, Siegfried wrote: > Hello, > > I need to create an export / import system for my app, and just thought that > asking the list for some advices could help a lot. > > The CoreData database I have is fairly simple. No relationships, only 3 > entities with no more than 4 properties each: numbers and strings. So I think > exporting this as XML is the more appropriate solution. Also, it would allow > users make changes in the file easily. > > Are there any serious drawbacks from using this method? Or may a better > solution? What worries me most is the XML validation. It's not a high > priority, but having an at least decent XML is worthwhile. The big question: > A header saying XML version 1.0 is enough? Or do I need to create a DTD? > > Also, now on the mechanics, I think creating a mutable string and go > appending parts of the XML in a loop is adequate for this task, and using > NSXMLParser to parse it back should work. Indeed, the file will not be that > big (usually a few hundreds of KBs, really extremes cases are 1 or 2MB). > Well, at least I'm not aware of a framework to export / import CoreData, I > don't even think it is possible. > > Any "yes" or "no" on my ideas are really appreciated. > > Thanks, > > Best wishes, > > Siegfried How about using a property list file instead? Easier to import and export, and can be edited with tools such as Property List Editor, though your users might not know how to use it, or even have it. WT___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Exporting and Importing CoreData
On Mar 23, 2011, at 8:46 PM, Siegfried wrote: > On 23/03/2011, at 20:38, WT wrote: > >> On Mar 23, 2011, at 8:13 PM, Siegfried wrote: >> >>> Hello, >>> >>> I need to create an export / import system for my app, and just thought >>> that asking the list for some advices could help a lot. >>> >>> โฆ >> >> How about using a property list file instead? Easier to import and export, >> and can be edited with tools such as Property List Editor, though your users >> might not know how to use it, or even have it. >> >> WT > > I was considering using it initially, but as you've stated that would make > things a bit more complicated when it comes to editing. XML would be ideal. > Also, the final file would be less verbose (not filled with nested dicts and > key value pairs). If you save your property list as XML and not as a binary file, then it's still XML and can be edited equally with PLE or any text editor (though maintaining its property list format may be a challenge for your users). As for how verbose it would be, a simple structure such as what you mentioned shouldn't produce anything overly verbose, I think. I suggest you try some simple tests to see how you like the results. > I really don't know when it comes to building the system. Do you think it > would integrate with CoreData better? Or just mean less code to write? The > latter case is not a problem though :-) I'm not entirely sure because I'm relatively inexperienced with Core Data but I suspect that it would involve much less code than having to parse the input file yourself. > Thanks WT! Most welcome. :) WT ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: iOS - Hide Master view in a split view
On Mar 24, 2011, at 6:27 PM, Eric Gorr wrote: > I am trying to figure out how to hide the master view in a split view while > in landscape mode. Searching, I found the suggestion to try: > > [[master view] setFrame:CGRectMake(0, 0, 0, 0)]; > [[detail view] setFrame:splitBounds]; > > However, this does not appear to work. What exactly doesn't work? Hiding or resizing the detail view? > What is the recommend method for hiding the master view in landscape mode so > the detail view can make use of the entire screen? > > Thanks. I just ran a very quick test and the following code snippet successfully toggles between showing and hiding the master view: UIViewController* vc; vc = [splitViewController.viewControllers objectAtIndex: 0]; vc.view.hidden = !vc.view.hidden; All you need to do then is adjust the frame of the detail view, which is the object at index 1 in the array splitViewController.viewControllers. Of course, you want to make sure that this code only runs when the device orientation is landscape and you'll want to cache the two frames the detail view will be having. WT___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: iOS - Hide Master view in a split view
On Mar 24, 2011, at 8:18 PM, Eric Gorr wrote: >> On Mar 24, 2011, at 7:11 PM, WT wrote: >> >> I just ran a very quick test and the following code snippet successfully >> toggles between showing and hiding the master view: >> >> UIViewController* vc; >> vc = [splitViewController.viewControllers objectAtIndex: 0]; >> vc.view.hidden = !vc.view.hidden; >> >> All you need to do then is adjust the frame of the detail view, which is the >> object at index 1 in the array splitViewController.viewControllers. Of >> course, you want to make sure that this code only runs when the device >> orientation is landscape and you'll want to cache the two frames the detail >> view will be having. > > I don't think it is so easy to adjust the frame of the detail view > considering the above code fails. I did try this, and, you're right, the > master view will hide, but the detail view will not resize. Hmm... could it be that the detail view has the autoresize masks set in a way to prevent it from expanding to the left? The solution might be as simple as just (re)setting them appropriately in which case you don't need any setFrame: code at all and hiding/showing the master view would suffice. I can't try that right now but, if you do, please share the outcome.___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Help with Custom Control
On Mar 24, 2011, at 12:10 AM, Carlos Eduardo Mello wrote: > Hi, > > I built a special control with a custom view and several parts, including > standard controls and some subviews. The thing does special displaying and > animation, and needs to be connected to other parts of the UI and to the > document controller. The set up works very nicely. Isolating it as a unit > helped me debug minor drawing bugs and make its internal behaviour very > consistent. However, I need to use several of these in the UI, so the whole > wiring business involves dozens of connections in IB. Hence my questions: > > 1. Is there a way to make a custom NSView send IBActions as if it were one of > the standard controls? > > 2. Is there a simple way to turn my little device into something I can add to > the library and reuse in several places. The idea would be to treat it as > aunit and be able to just wire an Action to the file's owner. > > 3. The way it is working right now is through a triple delegation - I need to > have a mouse up event initiated in a subview of my custom view trigger an > action in the enclosing view which is in turn forwarded to the controller. > > A, B and C are Custom Views > > A contains B, B contains C; > B is C's delegate, A is B's delegate, > File's Owner is A's delegate; > Clicking C sends a message to F.O. > > It works, but I was wondering if the design is not too complicated? (I am > trying to keep each part from having to "know" about other part's workings). > > I'd appreciate any ideas... If you're working with XCode 3.x, you can write an Interface Builder plugin for your custom view. I'm sure there are good tutorials online on how to create them. In XCode 4, however, IB plugins aren't yet supported. WT___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Help with Custom Control
On Mar 25, 2011, at 5:55 PM, Sean McBride wrote: > On Fri, 25 Mar 2011 17:46:04 -0300, WT said: > >> If you're working with XCode 3.x, you can write an Interface Builder >> plugin for your custom view. I'm sure there are good tutorials online on >> how to create them. In XCode 4, however, IB plugins aren't yet supported. > > "yet"? Why do you think they are coming back? They've been gone since > the first Xcode 4 seed and the Xcode 4.0.1 read me says they are deprecated. > > (Which, of course, totally sucks!) I'm downloading 4.0.1 at this very moment so I didn't know that IB plugins are officially deprecated. That really indeed sucks. WT___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Cocoa alternative for method aliasing?
On Mar 29, 2011, at 4:25 PM, Matt Neuburg wrote: > On Tue, 29 Mar 2011 11:20:31 -0700, Lou Zell said: >> I have a subclass of UIButton, call it MyButton, that I would like to >> function as a vanilla UIButton but also pass touch events to the next >> responder (I'm interested in eventually getting the events in >> UIViewController). I can do something like this in MyButton: >> >> -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event >> { >> [[self nextResponder] touchesBegan:touches withEvent:event]; >> } > > Don't do that. The way to pass touches up the responder chain is by calling > super. This will do exactly what you're after, I think. > > However, as already implied, you might be better off with a different > architecture. It isn't at all clear why you'd do what you're describing. Let > the button act as a button. If you need further information about what's > going on, consider a gesture recognizer, perhaps, or just use the button's > control events. In any case there should be no need to interfere at the very > low level of the touches... responder methods. There are *many* ways to > interfere with aspects of touch delivery; they are quite interesting, but be > careful or you'll break something. > > m. Moreover, according to the Event Handling Guide for iOS, http://developer.apple.com/library/ios/#documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/MultitouchEvents/MultitouchEvents.html "Important: If your custom responder class is a subclass of UIView or UIViewController, you should implement all of the methods described in โThe Event-Handling Methods.โ If your class is a subclass of any other UIKit responder class, you do not need to override all of the event-handling methods; however, in those methods that you do override, be sure to call the superclass implementation of the method (for example, super touchesBegan:touches withEvent:theEvent];). The reason for this guideline is simple: All views that process touches, including your own, expect (or should expect) to receive a full touch-event stream. If you prevent a UIKit responder object from receiving touches for a certain phase of an event, the resulting behavior may be undefined and probably undesirable." and, further down, "Handling Events in Subclasses of UIKit Views and Controls If you subclass a view or control class of the UIKit framework (for example, UIImageView or UISwitch) for the purpose of altering or extending event-handling behavior, you should keep the following points in mind: - Unlike in a custom view, it is not necessary to override each event-handling method. - Always invoke the superclass implementation of each event-handling method that you do override. - Do not forward events to UIKit framework objects." W.___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: UIView size after rotation
On Mar 30, 2011, at 8:19 AM, Remco Poelstra wrote: > Hi, > > In my UIVIewController > -(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation > duration:(NSTimeInterval)duration, I need to know the size of the view after > it's rotated. Is there a way to calculate it if it can not be requested? The > view's bounds are still in the old orientation, although the orientation > property is already updated. > Thanks in advance. > > Regards, > > Remco Poelstra A view is a rectangular area so its width and height are exchanged after a 90-degree rotation (which is what happens when you go from landscape to portrait or portrait to landscape). The only other consideration is that the view may be clipped to its superview's bounds after the rotation. So, to figure out a view's size after the rotation, exchange its width and height then clip the view to its superview's bounds after the rotation. There is a recursive element here in that you might have to do this to every view in the view hierarchy above your view-of-interest, ending at the window level. Also, make sure to use the correct frames or bounds, and the correct coordinate systems. WT ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: UIView size after rotation
On Mar 30, 2011, at 8:19 AM, Remco Poelstra wrote: > Hi, > > In my UIVIewController > -(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation > duration:(NSTimeInterval)duration, I need to know the size of the view after > it's rotated. Is there a way to calculate it if it can not be requested? The > view's bounds are still in the old orientation, although the orientation > property is already updated. > Thanks in advance. > > Regards, > > Remco Poelstra A view is a rectangular area so its width and height are exchanged after a 90-degree rotation (which is what happens when you go from landscape to portrait or portrait to landscape). The only other consideration is that the view may be clipped to its superview's bounds after the rotation. So, to figure out a view's size after the rotation, exchange its width and height then clip the view to its superview's bounds after the rotation. There is a recursive element here in that you might have to do this to every view in the view hierarchy above your view-of-interest, ending at the window level. Also, make sure to use the correct frames or bounds, and the correct coordinate systems. WT Important correction: you don't really want to actually clip any of the views, but clip a copy of their frame rectangles. After all, you just want to compute the results, not make them happen. WT___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Click in underlying document while sheet displayed?
On Mar 30, 2011, at 9:01 PM, Graham Cox wrote: > Hi all, > > I have a situation where I present a sheet dialog. The sheet asks the user > for some input values to perform a "polar duplicate" of a graphic object in > the underlying document (number of copies, rotation increment, etc). One of > the parameters is the centre point, and I figure a nice way to allow the user > to set this is to allow them simply to click in the document which enters the > value of that point into the dialog's text fields. > > The problem is of course, how to do this while the sheet is showing, since it > grabs all the events. It would be acceptable (and probably necessary) to have > a special mode a bit like Color Panel's sampling click mode for doing this. > > Just looking for inspiration on an approach to take... > > --Graham Hi Graham, if I understand correctly what you're trying to do, it's similar to an app I wrote quite some time ago. In that app, I was creating fractals and needed a means for the user to set the point around which to zoom in. The way I solved it was to have a smaller-scale version of the full image already rendered on the window, appearing as a custom view on the sheet. Of course, rendering the smaller-scale version need not be done in much detail. That avoids the issue of getting a click through the sheet. Maybe you could try something similar. Hope this helps. WT___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Can't keep untitled windows from opening!
On Mar 31, 2011, at 1:25 PM, Carlos Eduardo Mello wrote: > Hi everyone, > > I've implemented both methods bellow, but my document-based app still opens > untitled windows at start-up and when reactivated from the dock. The methods > are placed in the window's delegate (MyDocument.m) but they never get called. > Does anybody have an idea why this is happening? > > - (BOOL)applicationShouldOpenUntitledFile:(NSApplication *)sender > { > NSLog(@"Calling [applicationShouldOpenUntitledFile]..."); > return NO; > } > > - (BOOL)applicationShouldHandleReopen:(NSApplication *)sender > hasVisibleWindows:(BOOL)flag > { > NSLog(@"Calling [applicationShouldHandleReopen]..."); > return NO; > } > > Thanks, > > Carlos. Are you sure the window delegate is being set correctly and isn't nil? WT ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Seeking advice for how to implement "notification" upon completion of asynchronous upload
On Mar 31, 2011, at 9:08 PM, Chris Markle wrote: > Still fairly new here to iOS and Objective-C programming, so looking > for some advice to help keep me from going down the wrong road(s)... I > would like to build an Objective-C class or classes to perform a file > upload using a non-standard protocol. It would run the upload > asynchronously and would need to notify the caller upon completion. I > see a variety of techniques used or discussed for this and I was > hoping to get some advice on which pattern or patterns I should use > and which I should stay away from. I have no issue with using stuff > that only runs on the latest iOS or OS X systems, so supporting older > OS's in not a concern for me. > > I see in particular: > > 1. delegates - e.g., NSURLConnection connection:didFailWithError: and > connectionDidFinishLoading:, or similar ones in ASIHTTPRequest > requestFinished or requestFailed > > 2. blocks - e.g., ASIURLRequest completionBlock or failedBlock, or > ALAssetsLibrary assetForURL:resultBlock:failureBlock: (ASIHTTPRequest > actually implements delegates and blocks and allows you to mix and > match them.) > > 3. KVO (key-value observation) - e.g., some service where you observe > an isFinished property > > 4. Notifications (NSNotificationCenter, etc.) - haven't really seen > this used much but a lot of people seem to talk about it as a good > approach > > There are probably other techniques as well... > > For a new, modern API which approach or approaches should I use or not > use? I suppose my main interest here is to use something that's > flexible to the programmer that uses my API, and something that is > conventional ion its approach so that the programmer is using > something normal and not unusual. > > Thanks in advance for any counsel on this... > > Chris Hi Chris, I've written a fairly general Downloader class that takes in a url and some identifying token (so you can recognize the Downloader instance later on) and asynchronously downloads the url's content. It invokes methods on its delegate when it's done and on fail, passing it the data if the download succeeded. You can create multiple instances and they'll work independently. It also automatically keeps track of maintaining state for the network activity indicator (and does so in a thread-safe manner, even with many Downloader instances doing their thing). It works great, for instance, when you want to populate the rows of a table view with some downloaded data (eg, images from a web service), in which case you'd use the row's index path as the identifying token. You can then fire as many Downloader instances as there are visible rows and update each row as its downloader is done. Hope this helps. WT // Downloader.h // Copyright 2010 Wagner Truppel. All rights reserved. // Use/change as you see fit, but at your own risk. // Usage: // Downloader* downloader = [[Downloader alloc] init]; // downloader.idToken = ... // downloader.urlStr = ... // downloader.delegate = ... // [downloader startDownload]; // If there's a need to abort the download, invoke -stopDownload on // the instance in question. // Note: the public methods are NOT thread safe. #import @protocol DownloaderDelegate; // = // @interface Downloader: NSObject { @private id delegate_; id idToken_; NSString* urlStr_; NSURLConnection*connection_; NSMutableData* activeData_; BOOLisDownloading_; } // // @property (readwrite, nonatomic, assign) id delegate; @property (readwrite, nonatomic, retain) id idToken; @property (readwrite, nonatomic, retain) NSString* urlStr; // // - (void) startDownload; - (void) stopDownload; @end // = // @protocol DownloaderDelegate // NOTE: these are invoked and executed in the main thread. - (void) downloader: (Downloader*) downloader didFinishDownloadingData: (NSData*) data; - (void) downloader: (Downloader*) downloader failedWithError: (NSError*) error; @end // = // // Downloader.m // Copyright 2010 Wagner Truppel. All rights reserved. // Use/change as you see fit, but at your own risk. #import "Downloader.h" // = // // Keeps track of the number of active connections so we can keep the // network activity indicator on when there are active connections. static NSInteger stConnectionCount =
Re: (no subject)
On Apr 1, 2011, at 1:29 AM, Rikza Azriyan wrote: > Anyone could help me,, > I want to handle touch drag event programatically, for example in ibooks > reader, we use fingertips for navigating to next/prev page by sliding the > screen to the left/right direction. > I want to handle this event within my code, such as give the first cordinate > in A(180,45) and the last cordinate A'(90,188), means i do slide on sceen > from A to A'. > Anyone can help me how to do it? > > Thanks in Advance > > Rikza Azriyan > Student of Sriwijaya University > Palembang, Indonesia You can use a UIGestureRecognizer for this, and it's very easy. WT___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Seeking advice for how to implement "notification" upon completion of asynchronous upload
On Apr 1, 2011, at 12:47 PM, Chris Markle wrote: > WT, > > Thanks for the code! Hello again, Chris. You're most welcome! > So of the approaches: > >>> 1. delegates >>> 2. blocks >>> 3. KVO >>> 4. Notifications > > you went with delegates (didFinishDownloadingData: and > failedWithError:) for completion notification. > > Has this worked out well for others that have used this code? I can't speak for other people but delegation for situations such as this one has served me well in numerous occasions. > Did you consider any of the other alternatives and if so what made you go with > the delegate approach? I didn't exactly consider the other alternatives since delegation is the standard approach when one needs to offload work to other objects, but if I had to defend why delegation is the best approach in this case, here's what I'd say: KVO, as I understand it (I'm not very experienced with the KVO/KVC technologies), is best suited to observe changes in object *properties*, and not so much as a means to offload work to another object. The blocks API is great but it doesn't lend itself easily to much reusability. Sure, you can create a block, give it a name, and pass it around, but you don't want your block to have a ton of code. If you look at the majority of examples of block use, blocks are typically small sections of code. Besides, at the time I wrote the Downloader class, I wasn't aware of the blocks API (it was before WWDC 2010). Notifications are best suited for situations when a potentially large number of objects may be interested in an event or situation caused by a single object and you don't want to couple the producer to the consumers of those events. In my particular case (which happens to be *very* common), my goal was very clear: I had a table view controller managing a table view and I needed to fill the rows of that table view with data coming from the web. Since each row would have different data, I needed a means of independently downloading different bits of data. Of course, I could have written all the downloading code inside my custom table view controller class, but that's not a very reusable approach. Moreover, I'm a firm believer that each class should have as few and as well-defined responsibilities as possible. Writing all the downloading code inside the table view controller class would clutter the table view controller class with too many responsibilities. Much better is to create a class with the single responsibility of managing downloads in such a way that each instance is responsible for downloading data from a single url. But, then, how to coordinate the responses so that, when each downloader object is done or fails, the table view controller gets notified? Note that in this case we have several producers (the downloader objects) and one consumer (the table view controller), rather than one producer and several consumers. The notification approach is best used in the latter case. So, the natural approach here is to make the one consumer (the table view controller) the delegate of each of the producers (the downloaders). To summarize the advantages, you get code reusability, division of class responsibilities, decoupling of classes (the Downloader class knows nothing about the table view controller class), and you solve the many-producers/one-consumer problem in a natural and simple way. If I may make a suggestion, I think you might benefit from reading Cocoa Design Patterns by Erik Buck and Donald Yacktman a book that goes into great detail on the various so-called design patterns commonly used in Cocoa and Cocoa Touch programming. Hope this helps. WT___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Trying to subclass UISwitch
On Apr 4, 2011, at 1:20 PM, Philip Ershler wrote: > Hi, > After beating my head against the wall trying to subclass UISwitch, so > that I might change the "text" for the two states, I finally noticed that > there is a statement in the docs that UISwitch cannot be subclassed. (Please > no wise cracks that I should have seen that straight away, I get to claim old > eyes). So now I have come to realize that UISwitch is just a special case of > UISlider. > I see that it is possible to set images for all the different parts of > a UISlider. I'd like to make a UISlider look just like a UISwitch. Is there > an easy way to get the UIImage specs so that I can build a UISlider that > looks just like a UISwitch just with different ON and OFF "text". I'm sorry > if this is a real naive question. > > Thanks, Phil Hi Phil, I filed a request to Apple's bug system precisely for this functionality some 2 years ago, and got a reply back saying that it was a duplicate of bug ID# 5792695. I'm still waiting, but I suppose Apple is going to get to it at some point and offer a customizable UISwitch. Back then, my solution was to use a UISegmentedControl with two tabs but I see now that RCSwitch looks awesome and is probably a better alternative. Regards, WT___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Localized sorting of a Core Data entity
On Apr 7, 2011, at 3:23 PM, Chase Latta wrote: > Also, I don't actually know if you can register to receive notifications when > the user changes their language preference You can: NSCurrentLocaleDidChangeNotification WT === autoupdatingCurrentLocale Returns the current logical locale for the current user. + (id)autoupdatingCurrentLocale Return Value The current logical locale for the current user. The locale is formed from the settings for the current userโs chosen system locale overlaid with any custom settings the user has specified in System Preferences. The object always reflects the current state of the current user's locale settings. Discussion Settings you get from this locale do change as the userโs settings change (contrast withcurrentLocale). Note that if you cache values based on the locale or related information, those caches will of course not be automatically updated by the updating of the locale object. You can recompute caches upon receipt of the notification (NSCurrentLocaleDidChangeNotification) that gets sent out for locale changes (see Notification Programming Topics to learn how to register for and receive notifications). Availability โข Available in iOS 2.0 and later. See Also โข + systemLocale โข + currentLocale Declared In NSLocale.h ===___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Lockless thread-safe accessor using blocks: how to?
Hi all, I've started to use GCD in my projects and I found myself using a certain pattern that I now realize isn't actually thread safe. The goal is to write a thread-safe lazy accessor without using locks, @synchronized, or an atomic property. At first I thought that - (SomeObjType) foo { __block SomeObjType foo = nil; dispatch_sync(queue, ^{ // retrieve bah if (nil == bah) { // compute and store bah } foo = bah; }); return foo; } would do it. Here, bah is some resource that may be changed by multiple threads and queue is a serial GCD queue defined as a static variable in the class where this accessor is defined. The queue is not any of the global queues, but is created by the class. I see two problems with this pattern. The first is that if the method gets invoked already in the queue's automatic thread, there will be a deadlock. That's easy to fix, by wrapping the dispatch call into a function that tests queue against the currently executing queue and simply executes the block when they coincide. The second problem is that the pattern isn't actually thread safe. If two threads (that aren't the automatic thread of the queue) enter the accessor, two blocks will be enqueued serially. The two threads will then block, waiting for their blocks to finish executing. So far so good but when the first block finishes, it could happen that the first thread blocks until the second block finishes, at which time the foo value computed by the first block will have been replaced by the value computed by the second block, since foo is shared among all blocks that captured it. Thus, when the first thread resumes, it will report the wrong foo value. So, what is the correct pattern to write a thread-safe lazy accessor without using locks, @synchronized, or an atomic property? Thanks in advance. WT___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Lockless thread-safe accessor using blocks: how to?
Hi Jonathan, thanks for replying. On Apr 14, 2011, at 11:12 AM, Jonathan Taylor wrote: > I am afraid I am not completely sure what you mean by your first problem, That's ok. As I said, it's easy to fix. I don't want to get sidetracked here by going through it in detail. If you'd like to discuss that problem in more detail, we can do it off the list. > but hopefully my answer to your second one sidesteps your concern there. In > answer to your second (once I had parsed out the two different uses of the > word "block" in what you said!)... Yeah, the use of 'block' as both a verb and a noun is a bit confusing. Blame Apple for that... :) > If I understand you correctly, what you're saying about your variable > "__block SomeObjType foo" is not true. Regardless of the __block qualifier, > foo is effectively a stack-based variable, so two simultaneously-executing > threads have their own independent instance of that variable. There can be no > "cross-talk" between the variables in separate threads - all you are doing is > enabling the block that a given thread executes to have access to that > specific thread's stack variable. I'm afraid you're incorrect there. According to the documentation (or, more precisely, my understanding of the documentation), a variable qualified with __block starts in the stack but is moved to the heap, precisely because it's shared by all blocks capturing it and by all function scopes where it's declared. Therefore, I do not believe "two simultaneously-executing threads have their own independent instance of that variable" to be true. > However I don't think you should need to do this anyway. I would change your > code to something like this: > > - (SomeObjType) foo > { > dispatch_sync(queue, > ^{ > // Code in this block ensures bah is valid > if (nil == bah) > { > // Code to compute and store bah goes here > } > }); > > return bah; > } I don't see how that could possibly work as is because bah is out of scope by the time the return statement is executed. Perhaps you meant that bah is an ivar or property declared in the same class as the accessor. I'm suddenly drawing a blank here because I considered this before and came to the conclusion that it wouldn't work but now I can't remember why I thought that way. I need to think this through a bit more. Thanks again for your input. WT___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Lockless thread-safe accessor using blocks: how to?
On Apr 14, 2011, at 1:19 PM, Jonathan Taylor wrote: > I tested this out before replying as I wasn't 100% certain. It may be that we > have misunderstood each other somehow, but the following code (in a clean new > project) was what I used to confirm to myself that two concurrently-executing > threads have independent instances of the variable: > http://www.dur.ac.uk/j.m.taylor/block_test_code.m More likely, I've misunderstood the documentation. It's happened before, many times. :) I looked at your code only briefly now but will return to study it in detail later (kinda busy right now). I must say that I'm confused now more than before, because I really thought that the __block qualifier meant that there is only one instance of that variable, shared by all scopes that declare it and shared by all blocks that capture it. >>> However I don't think you should need to do this anyway. I would change >>> your code to something like this: >>> >>> - (SomeObjType) foo >>> { >>> dispatch_sync(queue, >>> ^{ >>> // Code in this block ensures bah is valid >>> if (nil == bah) >>> { >>> // Code to compute and store bah goes here >>> } >>> }); >>> >>> return bah; >>> } >> >> I don't see how that could possibly work as is because bah is out of scope >> by the time the return statement is executed. Perhaps you meant that bah is >> an ivar or property declared in the same class as the accessor. I'm suddenly >> drawing a blank here because I considered this before and came to the >> conclusion that it wouldn't work but now I can't remember why I thought that >> way. I need to think this through a bit more. > OK, well since you do not declare bah locally, and from what you are doing it > is presumably meant to be persistent, I assumed that it was indeed a property > (or a global?). If you are doing something else with it (though I'm not quite > sure what...) then obviously what I wrote may be wrong... No, actually you are totally correct here. As it happens, I do use the pattern you suggest, in several places where the conditions are precisely those you laid out: the ivars are meant to be instantiated only once and never released. It's in other cases where those conditions break that I'm struggling with. Clearly I need to refine my understanding of blocks and discussions like this greatly help. Thanks again. WT___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Lockless thread-safe accessor using blocks: how to?
Hi David, thanks for pitching in. On Apr 14, 2011, at 1:40 PM, David Duncan wrote: >> I tested this out before replying as I wasn't 100% certain. It may be that >> we have misunderstood each other somehow, but the following code (in a clean >> new project) was what I used to confirm to myself that two >> concurrently-executing threads have independent instances of the variable: >> http://www.dur.ac.uk/j.m.taylor/block_test_code.m > > On this point Jonathan is correct. What __block does is ensure that a > declared variable has the ability to survive its stack frame, not that a > variable of that name is shared with all invocations of that stack frame. If > you want a variable that will be shared with all instances of that stack > frame, you want the "static" qualifier. I see. It's final, then: I have misunderstood the documentation. Thank you both for pointing me in the right direction. However I don't think you should need to do this anyway. I would change your code to something like this: - (SomeObjType) foo { dispatch_sync(queue, ^{ // Code in this block ensures bah is valid if (nil == bah) { // Code to compute and store bah goes here } }); return bah; } > > > Fundamentally however, this will not work. If you want to do lazy > initialization of a variable with thread safety then you should use > dispatch_once() to initialize the variable. This is also not something you > can do with a __block or static variable (unless you want all instances to > have the same value, which seems to be against the way you've declared the > method). Basically you need to do this: > > - (SomeObjectType) foo > { > dispatch_once(&ivar_predicate, ^ { ivar_value = /* initialization */ }); > return ivar_value; > } I looked at dispatch_once() at one point, but I'm still confused by how it works. In any case, here's an actual example of where I use the pattern Jonathan suggested, and I can't see why it would not work. stSerialQueue is a static variable in the class where -shortStyleDateFormatter is declared. shortStyleDateFormatter_ is an ivar in that same class, backing the property for which the accessor is being written. WLT_GCDUtils' +dispatchToQueue: async: guarantees that the dispatch is deadlock-free regardless of which thread the block is executed in. - (NSDateFormatter*) shortStyleDateFormatter; { [WLT_GCDUtils dispatchToQueue: stSerialQueue async: NO block: ^{ if (nil == shortStyleDateFormatter_) { shortStyleDateFormatter_ = [[NSDateFormatter alloc] init]; [shortStyleDateFormatter_ setLocale: [NSLocale autoupdatingCurrentLocale]]; [shortStyleDateFormatter_ setDateStyle: NSDateFormatterShortStyle]; } }]; return shortStyleDateFormatter_; } // In WLT_GCDUtils.m + (void) dispatchToQueue: (dispatch_queue_t) queue async: (BOOL) async block: (void (^)(void)) block; { if (dispatch_get_current_queue() != queue) { if (async) { dispatch_async(queue, block); } else { dispatch_sync(queue, block); } } else // already in target queue { // Just in case we might need one... NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; block(); [pool release]; } } Thanks again for your help. WT___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Lockless thread-safe accessor using blocks: how to?
Hi Dave, thanks for replying. I must say some of what you said went above my head. :) On Apr 14, 2011, at 2:02 PM, Dave Zarzycki wrote: >> The first is that if the method gets invoked already in the queue's >> automatic thread, there will be a deadlock. That's easy to fix, by wrapping >> the dispatch call into a function that tests queue against the currently >> executing queue and simply executes the block when they coincide. > > Actually, this isn't easy to fix due to X->A->B->A problems, where X is the > current queue, then A, then B, and then the code deadlocks trying to > dispatch_sync() against A "because it isn't the current queue". Why isn't the following deadlock-free? // In WLT_GCDUtils.m + (void) dispatchToQueue: (dispatch_queue_t) queue async: (BOOL) async block: (void (^)(void)) block; { if (dispatch_get_current_queue() != queue) { if (async) { dispatch_async(queue, block); } else { dispatch_sync(queue, block); } } else // already in target queue { // Just in case we might need one... NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; block(); [pool release]; } } >> The second problem is that the pattern isn't actually thread safe. If two >> threads (that aren't the automatic thread of the queue) enter the accessor, >> two blocks will be enqueued serially. The two threads will then block, >> waiting for their blocks to finish executing. >> >> So far so good but when the first block finishes, it could happen that the >> first thread blocks until the second block finishes, at which time the foo >> value computed by the first block will have been replaced by the value >> computed by the second block, since foo is shared among all blocks that >> captured it. >> >> Thus, when the first thread resumes, it will report the wrong foo value. > > Can you please provide a compilable test case? I don't have an actual sample case where it has happened. Admittedly, this was just a thought experiment. Thanks again for your help. WT ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Lockless thread-safe accessor using blocks: how to?
On Apr 14, 2011, at 2:09 PM, David Duncan wrote: > On Apr 14, 2011, at 10:02 AM, WT wrote: > >> I looked at dispatch_once() at one point, but I'm still confused by how it >> works. > > dispatch_once uses a predicate (just a flag) to determine if it should run > the block or not. If that flag is false, then it sets the flag to true and > executes the block. If the flag is true, it does nothing. What makes > dispatch_once useful over a simple if statement is that it ensures that if > you execute dispatch_once concurrently from multiple threads that flag gets > updated exactly once, and the block gets called exactly once. Thanks for explaining it, David. The bit that was throwing me off is the predicate part. I understand now that all I need is to declare a static variable of the appropriate type and pass a pointer to it to dispatch_once(). Here's another question, though. In the example I've mentioned already (reproduced below so you won't have to look it up in a previous message) stSerialQueue is a static variable in the class where -shortStyleDateFormatter is declared. shortStyleDateFormatter_ is an ivar in that same class, backing the property for which the accessor is being written. WLT_GCDUtils' +dispatchToQueue: async: guarantees that the dispatch is deadlock-free regardless of which thread the block is executed in. - (NSDateFormatter*) shortStyleDateFormatter; { [WLT_GCDUtils dispatchToQueue: stSerialQueue async: NO block: ^{ if (nil == shortStyleDateFormatter_) { shortStyleDateFormatter_ = [[NSDateFormatter alloc] init]; [shortStyleDateFormatter_ setLocale: [NSLocale autoupdatingCurrentLocale]]; [shortStyleDateFormatter_ setDateStyle: NSDateFormatterShortStyle]; } }]; return shortStyleDateFormatter_; } // In WLT_GCDUtils.m + (void) dispatchToQueue: (dispatch_queue_t) queue async: (BOOL) async block: (void (^)(void)) block; { if (dispatch_get_current_queue() != queue) { if (async) { dispatch_async(queue, block); } else { dispatch_sync(queue, block); } } else // already in target queue { // Just in case we might need one... NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; block(); [pool release]; } } the locale is autoupdating. The instance of the class in question listens to notifications of the locale changing, invokes a method that releases and nillifies all the ivars such as shortStyleDateFormatter_ when those notifications arrive, and then posts its own notification so that the rest of the application can update its UI. Naturally, the rest of the application may need to invoke -shortStyleDateFormatter and similar methods and the work needs to be redone for the new locale. >From my understanding of dispatch_once(), I can't use it for this purpose >because it really executes the block only once in the application's life time. WT___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Lockless thread-safe accessor using blocks: how to?
Thanks to everyone who responded. Two things are clear: there is no one-size-fits-all answer here, and I need to do a more detailed analysis of the needs in my project. WT___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Proper way to create a singleton without @synchronized ?
After David Duncan explained dispatch_once() more clearly than the available documentation, I thought I'd give it a second look. Among other things, I wanted to replace my usage of @synchronized singletons, and dispatch_once() seemed the perfect mechanism for that. So, I put together the class at the end of this message. >From the testing I've done - creating several threads, each invoking either >[MySingleton sharedInstance] or [[MySingleton alloc] init] after a randomly >selected sleep time, and running the test anew several times - it appears to >behave correctly, that is, the same instance is used in every thread, it's >always properly initialized (all "instances" have the same value for >someInteger), and each of the three dispatch_once() blocks is executed exactly >once, no matter how many threads were created. My question for you all is then whether this is indeed correct, or whether I'm missing something that my testing may not have revealed. Thanks in advance. WT === // MySingleton.h: #import @interface MySingleton: NSObject { NSUInteger someInteger_; } @property (readwrite, nonatomic, assign) NSUInteger someInteger; + (MySingleton*) sharedInstance; @end // MySingleton.m: #import #import "MySingleton.h" #import #import static MySingleton* stSharedInstance = nil; static dispatch_once_t stSharedInstanceInvoked; static dispatch_once_t stAllocWithZoneInvoked; static dispatch_once_t stInitInvoked; @implementation MySingleton @synthesize someInteger = someInteger_; + (MySingleton*) sharedInstance; { dispatch_once(&stSharedInstanceInvoked, ^{ NSLog(@"+sharedInstance block entered"); // Assignment done in +allocWithZone:. // The autorelease message is sent to prevent XCode's // static analyzer from issuing a warning about a possible // memory leak. There is no leak, since the singleton is // not meant to be deallocated, and the autorelease message // does nothing, as per its overridden implementation below. self class] alloc] init] autorelease]; NSLog(@"+sharedInstance block exited"); }); return stSharedInstance; } + (id) allocWithZone: (NSZone*) zone; { dispatch_once(&stAllocWithZoneInvoked, ^{ NSLog(@"+allocWithZone: block entered"); stSharedInstance = [super allocWithZone: zone]; NSLog(@"+allocWithZone: block exited"); }); return stSharedInstance; } - (id) init; { __block id tempSelf = self; dispatch_once(&stInitInvoked, ^{ NSLog(@"-init block entered"); tempSelf = [super init]; if (tempSelf) { someInteger_ = random() % 1000; NSLog(@"Instance initialized"); } NSLog(@"-init block exited"); }); self = tempSelf; return self; } - (id) copyWithZone: (NSZone*) zone; { return self; } - (id) retain; { return self; } - (unsigned) retainCount; { return UINT_MAX; // Denotes an object that cannot be released. } - (void) release; { /* do nothing */ } - (id) autorelease; { return self; } @end ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Proper way to create a singleton without @synchronized ?
Hi Dave, thanks for replying. On Apr 17, 2011, at 12:18 AM, Dave DeLong wrote: > There are a whole bunch of ways to make singletons. Some are much more work > than others... The amount of work is of little concern for me in this case because the singleton class will become a template like its @synchronized version already is, so I only have to do the work once. > //if we overrode -init, then you could run into issues if you ever tried to > alloc/init a MySingleton multiple times True. > It's a lot shorter, because you don't have to worry about overriding all of > the memory management methods. As long as you correctly retain > and release this object, it will never cease to exist. The only reason why I have that particular implementation is that I've seen it done that way (but with @synchronized rather than dispatch_once()) in Apple's docs. Where exactly escapes me right now. Thanks again. WT ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Proper way to create a singleton without @synchronized ?
Hi Kyle, thanks for replying. On Apr 17, 2011, at 12:31 AM, Kyle Sluder wrote: > Do you really need a singleton, or just a default instance? A singleton. >> static MySingleton* stSharedInstance = nil; >> >> static dispatch_once_t stSharedInstanceInvoked; >> static dispatch_once_t stAllocWithZoneInvoked; >> static dispatch_once_t stInitInvoked; > > All of these could be made static variables within the method body, > increasing readability and reducing pollution of the global scope > without affecting storage longevity. It's the coding style I'm used to, listing the statically allocated variables at the top. I don't see how declaring them inside the methods that use them helps to reduce pollution of the global scope, since they have to be visible to different methods in the same compilation unit anyway. >> + (MySingleton*) sharedInstance; >> { >>dispatch_once(&stSharedInstanceInvoked, >>^{ >>NSLog(@"+sharedInstance block entered"); >> >>// Assignment done in +allocWithZone:. >>// The autorelease message is sent to prevent XCode's >>// static analyzer from issuing a warning about a possible >>// memory leak. There is no leak, since the singleton is >>// not meant to be deallocated, and the autorelease message >>// does nothing, as per its overridden implementation below. > > Rather than relying on -allocWithZone: to return the shared instance, > why not assign to stSharedInstance here? No reason other than that this implementation is based on the singleton implementation I saw in some Apple documentation. >>self class] alloc] init] autorelease]; > > You are in a class method. self == [self class], so no need to call +class > here. What if I'm trying to subclass this singleton? >> + (id) allocWithZone: (NSZone*) zone; >> { >>dispatch_once(&stAllocWithZoneInvoked, >>^{ >>NSLog(@"+allocWithZone: block entered"); >> >>stSharedInstance = [super allocWithZone: zone]; >> >>NSLog(@"+allocWithZone: block exited"); >>}); >> >>return stSharedInstance; > > Of course this means you can't subclass this class. Why not? As long as the subclass doesn't override +allocWithZone:, this shouldn't be a problem, no? >> - (id) init; >> { >>__block id tempSelf = self; > > Because the block is not going to be copied, you do not need to worry > about creating a __block version of self here. And since this is a > singleton, even if the block *were* copied (and thus self retained), > you still wouldn't care. > >> >>dispatch_once(&stInitInvoked, >>^{ >>NSLog(@"-init block entered"); >> >>tempSelf = [super init]; >> >>if (tempSelf) >>{ >>someInteger_ = random() % 1000; >>NSLog(@"Instance initialized"); >>} >> >>NSLog(@"-init block exited"); >>}); >> >>self = tempSelf; >>return self; >> } My first attempt was simply >> - (id) init; >> { >>dispatch_once(&stInitInvoked, >>^{ >>NSLog(@"-init block entered"); >> >>self = [super init]; >> >>if (self) >>{ >>someInteger_ = random() % 1000; >>NSLog(@"Instance initialized"); >>} >> >>NSLog(@"-init block exited"); >>}); >> >>return self; >> } but the compiler complained that self is read-only within the scope of the block. I needed a way to write to self and I couldn't redeclare self, hence a writable tempSelf. >> - (id) copyWithZone: (NSZone*) zone; >> { >>return self; > > By virtue of this implementation, you can't implement NSCopying in a > subclass. But you can't subclass this class anyway because of > +allocWithZone:. > >> } I can see why that might cause some problems but, then, semantically, a singleton shouldn't be something that you can duplicate anyway. >> - (unsigned) retainCount; >> { >>return UINT_MAX; // Denotes an object that cannot be released. > > Why bother? All this will do is mask any bugs where your singleton disappears. > >> } >> >> >> - (void) release; >> { >>/* do nothing */ > > Don't do this. As above, you're just masking cases where you > accidentally over-release your singleton. > >> } About these two, once again it all came from Apple's implementation in one of the docs. I read it, it made sense to me at the time, so I used it often. Now, I wanted to replace the use of @synchronized but didn't think of changing anything I didn't absolutely have to change. >> - (id) autorelease; >> { >>return self; >> } > > Look, you're going to great lengths to ensure you never create more > than one instance of this class. Is any of it really necessary? Well, it is if I need a true singleton and sometimes I do. In fact, I kinda often do. I tend to break down my code into classes with very well defined, and typically few, responsibilities. Often times, making them singletons simplifies my code. For
Re: Proper way to create a singleton without @synchronized ?
Hi Ken, On Apr 17, 2011, at 3:00 AM, Ken Thomases wrote: > On Apr 17, 2011, at 12:20 AM, WT wrote: > >> On Apr 17, 2011, at 12:31 AM, Kyle Sluder wrote: >> >>>> self class] alloc] init] autorelease]; >>> >>> You are in a class method. self == [self class], so no need to call +class >>> here. >> >> What if I'm trying to subclass this singleton? > > What about it? 'self' identifies the actual, dynamic object receiving the > message -- in this case, a class. It is not of the static type of the > @implementation block it occurs within. Put another way, [self class] is no > more dynamic than [self alloc]. Tell that to Erik Buck and Donald Yacktman, the authors of 'Cocoa Design Patterns'. They explicitly assert on the second paragraph of page 151 that [self class] is used instead of self to support instantiating the appropriate subclass. Clearly there is some confusion regarding this matter, even among people more experienced than I, so I don't feel so bad by being confused about it too. :) > + (id) allocWithZone: (NSZone*) zone; >>>> { >>>> dispatch_once(&stAllocWithZoneInvoked, >>>> ^{ >>>> NSLog(@"+allocWithZone: block entered"); >>>> >>>> stSharedInstance = [super allocWithZone: zone]; >>>> >>>> NSLog(@"+allocWithZone: block exited"); >>>> }); >>>> >>>> return stSharedInstance; >>> >>> Of course this means you can't subclass this class. >> >> Why not? As long as the subclass doesn't override +allocWithZone:, this >> shouldn't be a problem, no? > > How many stSharedInstance variables are there? How many > stAllocWithZoneInvoked dispatch_once predicates are there? Yes, of course. What threw me off was that Kyle's comment made it look like it was the implementation of +allocWithZone: itself that broke the ability to subclass and not the fact that I'm using a static variable that would be the same for all subclasses. > About these two, once again it all came from Apple's implementation in one of > the docs. I read it, it made sense to me at the time, so I used it often. > Now, I wanted to replace the use of @synchronized but didn't think of > changing anything I didn't absolutely have to change. > > Apple's guide for creating singletons has, historically, been much criticized > and then subsequently much revised. If you based your implementation on > that, you might consider the criticisms as well as the revisions. One > critique, as an example: > http://boredzo.org/blog/archives/2009-06-17/doing-it-wrong That is a very useful and interesting reference. Thank you for pointing me to it. I don't agree with every point the author makes, however. In particular, I agree with one of the commenters, who argues that overriding the memory management methods is a good thing. But that's again going into a philosophical discussion and I'd rater not go there here. Thanks again for your help. WT___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Proper way to create a singleton without @synchronized ?
On Apr 17, 2011, at 3:11 AM, Dave DeLong wrote: > This is a truly strange question. If you interpret a singleton to be "one and > only one", then it doesnt make much sense to ask about subclassing it, > because that would imply that you could instantiate one of the base type and > one of the sub type, thus making it not fit the definition of a singleton. That's only because, unlike java, obj-c doesn't have a way built into the language to enforce a class to be abstract. I can see valid reasons to subclass a singleton if that singleton is to be used as an abstract class and never be instantiated by itself. > However, if we put philosophical discussions aside and simply ask for a > maximum of one instance per class, then I'd probably do something like this: > instead of using a single static variable to hold your singleton, use a > mutable dictionary instead. The keys of the dictionary would be the name of > the class, and the corresponding values would be e singleton objects. > Override +allocWithZone: to either return the appropriate and existing > object, or capture the call to super and save it in the dictionary before > returning it. Of course, this would preclude any of the subclasses doing > [self release] and returning a new object, but that's probably an adequate > compromise. That's an interesting suggestion and it's something I'll consider it. Thanks for offering that suggestion. WT ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Proper way to create a singleton without @synchronized ?
> it's possible the base class could be an abstract class, perhaps providing > nothing except the ability for concrete subclasses to make singleton > instances of themselves Yes, that's precisely the use I have in mind, because it's the most common in my projects. WT On Apr 17, 2011, at 4:02 AM, Andy Lee wrote: > I'm not really following this thread, so I might be missing important > context, but I think it's possible the base class could be an abstract class, > perhaps providing nothing except the ability for concrete subclasses to make > singleton instances of themselves. You might reuse this class in different > applications that need singletons. Or you might have multiple singleton > classes within one application, all inheriting from the base class. Or within > your app you might use one concrete class as a temporary placeholder for > debugging, which would be replaced by the real class in production. > > --Andy > > On Apr 17, 2011, at 2:11 AM, Dave DeLong wrote: > >> This is a truly strange question. If you interpret a singleton to be "one >> and only one", then it doesnt make much sense to ask about subclassing it, >> because that would imply that you could instantiate one of the base type and >> one of the sub type, thus making it not fit the definition of a singleton. >> >> However, if we put philosophical discussions aside and simply ask for a >> maximum of one instance per class, then I'd probably do something like this: >> instead of using a single static variable to hold your singleton, use a >> mutable dictionary instead. The keys of the dictionary would be the name of >> the class, and the corresponding values would be e singleton objects. >> Override +allocWithZone: to either return the appropriate and existing >> object, or capture the call to super and save it in the dictionary before >> returning it. Of course, this would preclude any of the subclasses doing >> [self release] and returning a new object, but that's probably an adequate >> compromise. >> >> Dave >> >> Sent from my iPad >> >> On Apr 16, 2011, at 10:20 PM, WT wrote: >> >>> how would you implement a *true* singleton class that supports subclassing? ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Proper way to create a singleton without @synchronized ?
On Apr 17, 2011, at 12:03 PM, Kyle Sluder wrote: > On Apr 16, 2011, at 10:20 PM, WT wrote: > >> >> On Apr 17, 2011, at 12:31 AM, Kyle Sluder wrote: >> >>> Do you really need a singleton, or just a default instance? >> >> A singleton. > > Okay, next question: why? Is there a reason that you can't replace all your > calls to +alloc/-init with +sharedInstance? I suppose you meant to say replace alloc/init calls with +defaultInstance. I think I already explained why: I like to have few and well-defined responsibilities for each class. A true singleton - that's written, tested, and debugged once - has a very specific responsibility and is very reusable, even when it's used in place of a default instance. >>> All of these could be made static variables within the method body, >>> increasing readability and reducing pollution of the global scope >>> without affecting storage longevity. >> >> It's the coding style I'm used to, listing the statically allocated >> variables at the top. I don't see how declaring them inside the methods that >> use them helps to reduce pollution of the global scope, since they have to >> be visible to different methods in the same compilation unit anyway. > > Because variables are scoped to their enclosing block. Top-level variables > are global scoped. Variables within blocks are accessible only within that > function's scope. Top-level variables are global to the compilation unit, in this case the .m file. That's hardly polluting the global scope. > If you find you only use a global static variable from within one function, > you lose nothing by moving that static variable into the function. Well, > except for the ability to access it from other functions, but you weren't > using that. You're correct about the dispatch_once() predicates, but the singleton sharedInstance static is accessed by different methods so it must be declared at the top level of the .m file. >>> Rather than relying on -allocWithZone: to return the shared instance, >>> why not assign to stSharedInstance here? >> >> No reason other than that this implementation is based on the singleton >> implementation I saw in some Apple documentation. > > Mike Ash had a good blog post about singletons which you may want to read: > http://www.mikeash.com/pyblog/friday-qa-2009-10-02-care-and-feeding-of-singletons.html Thank you for that link. That and the article Ken suggested will be my light afternoon reading for this Sunday. :) >>> You are in a class method. self == [self class], so no need to call +class >>> here. >> >> What if I'm trying to subclass this singleton? > > Hint: +class is defined to return self. I'll say here what I said in my reply to Ken... Tell that to Erik Buck and Donald Yacktman, the authors of 'Cocoa Design Patterns'. They explicitly assert on the second paragraph of page 151 that [self class] is used instead of self to support instantiating the appropriate subclass. Clearly there is some confusion regarding this matter, even among people more experienced than I, so I don't feel so bad by being confused about it too. :) >>> Of course this means you can't subclass this class. >> >> Why not? As long as the subclass doesn't override +allocWithZone:, this >> shouldn't be a problem, no? > > See Dave's reply. I get that the single static variable precludes subclassing. It was your singling out +allocWithZone: that made me think that there was something specific to it that prevented subclassing. >> but the compiler complained that self is read-only within the scope of the >> block. I needed a way to write to self and I couldn't redeclare self, hence >> a writable tempSelf. > > Bah. I swear one of these days I'll remember the const copy thing that > happens to non-__block variables. :) My use of blocks almost never touches > self, so the relatively few self gymnastics I see or use are about avoiding > leaks. As I said above, there are things that sometimes confuse even those who are more experienced programmers than I, so I've learned not to be surprised when I or others fall for traps like that. >> Well, it is if I need a true singleton and sometimes I do. In fact, I kinda >> often do. I tend to break down my code into classes with very well defined, >> and typically few, responsibilities. Often times, making them singletons >> simplifies my code. > > Making them singletons can never be simpler than just not creating more than > one instance of a regular class. It's amortized simplicity :) I'm a big fan
Re: Proper way to create a singleton without @synchronized ?
On Apr 17, 2011, at 12:57 PM, Scott Ribe wrote: > On Apr 16, 2011, at 9:04 PM, WT wrote: > >> Among other things, I wanted to replace my usage of @synchronized >> singletons... > > Why? As a learning experience, experimenting with GCD, what you're doing is > somewhat instructive. That's one of the reasons. > But your stated goal seems pointless to me. Whether you use @synchronized, > explicit NSLocks, pthread locks, OS spinlocks, OS atomics, memory barriers, > or inject a tiny bit of C++ (the ability to assign the result of a > computation to a static) + a compiler option (ensure statics are only > initialized once) is unlikely to affect anything. That's not what I keep reading/hearing. Apple's made a big push for GCD in WWDC 2010, even on iOS devices. >> I have a singleton that takes care of all things core data (well, all things >> that can be done generically). Likewise, I have a singleton for locale >> "utilities". All my number and date formatters are there, in one place, >> created once on demand and accessible everywhere else through the singleton. >> That's the kind of usage I have for singletons. > > Well, maybe it is time for a philosophical discussion. You could go through > all the work of making these into true singletons and calling a method to > access them for every single use, or you could initialize a handful of > globals at startup and just use them. I think that's an oversimplification of how things get used. See my reply to Kyle's last message for some examples of how/why I use singletons. WT ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Proper way to create a singleton without @synchronized ?
On Apr 17, 2011, at 3:52 PM, Joanna Carter wrote: > Hi guys > >> That's only because, unlike java, obj-c doesn't have a way built into the >> language to enforce a class to be abstract. I can see valid reasons to >> subclass a singleton if that singleton is to be used as an abstract class >> and never be instantiated by itself. > > Tell me; maybe it's my background in other languages, but I would tend to use > a "static class" as a singleton; or, at least, design a class with only class > methods/properties, with static "fields" declared in the @implementation > section of a class. > > Why this fascination with going to all the trouble of creating a singleton > rather than using the "static class" approach? > > Joanna Hi Joanna, not a fascination, but simply a preference and being used to coding that way. As for the "static class" idea, what happens if you need/want to subclass that class? Then you have to search for and change all the places in your code base that refer to it. WT___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: How do I disable Xcode 4's SVN support?
On Apr 17, 2011, at 4:23 PM, John Michael Zorko wrote: > > Hello, all ... > > I run my own SVN server, and I do my own SVN management. I would greatly > prefer that Xcode 4 not even try to talk to my SVN server, as it keeps asking > me to allow access to that key in my keychain, over and over and over and > over again. How can I disable Xcode 4's SVN support permanently? > > Regards, > > John Hi John, I believe that question is better suited for the XCode list rather than the Cocoa-Dev list. Nonetheless, here's my answer: for a radical solution such as what you're looking for, I think you can go to the Repositories panel of the Organizer window (hit cmd-shift-2 to get to the Organizer window) and delete XCode's knowledge of your repository. I haven't tried, so I don't know if that actually works. WT ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Proper way to create a singleton without @synchronized ?
On Apr 17, 2011, at 4:28 PM, Scott Ribe wrote: > On Apr 17, 2011, at 12:43 PM, WT wrote: > >> That's not what I keep reading/hearing. Apple's made a big push for GCD in >> WWDC 2010, even on iOS devices. > > Yeah, for actually performing tasks on background threads, which is not what > you're doing here. I am, insofar as my singletons are thread-safe. >> I think that's an oversimplification of how things get used. See my reply to >> Kyle's last message for some examples of how/why I use singletons. > > I saw that message and was responding to it. Why exactly do these classes of > yours need enforced singletons rather than single instances instantiated at > app initialization? What do you gain? I think I've explained my reasons. Perhaps they're not other people's reasons, perhaps they're not even good reasons. If for no other reason, consider this a learning experience for me, as you pointed out earlier. WT ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Proper way to create a singleton without @synchronized ?
On Apr 17, 2011, at 4:55 PM, Joanna Carter wrote: > Hi WT > >> what happens if you need/want to subclass that class? Then you have to >> search for and change all the places in your code base that refer to it. > > Hmmm, I have a problem with the idea of subclassing singletons. Does the > derived instance contain the same data as the base class; so that any > reference to the derived singleton is implicitly also a reference to the base > singleton? > > Joanna Don't get me wrong. I too see potential problems with subclassing singletons, both conceptually and in practice. In the case of my immediate needs, the base class would only and simply be a provider of singleton-ness, so to speak, that is, the ability for a/the (sub)class to have a single instance. What that subclass actually does is up to the subclass itself. This thread has taken a turn towards the subclassing issue because of something I wrote in a reply to Kyle but subclassable singletons are not terribly all that important to me. More important to me is to get the singleton-ness quality of a class done right, for some definition of "right." I can then turn that into a template file (in the XCode sense of templates) and cookie-cut it when I need different singleton classes for different purposes. And, as I pointed out elsewhere, getting the singleton-ness quality of a class done right, with all its quirks, is also a learning experience. In the end, that's probably the most honest reason I can give to pursue this. WT___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Proper way to create a singleton without @synchronized ?
Hi Quincey, thanks for pitching in. On Apr 17, 2011, at 4:58 PM, Quincey Morris wrote: > 1. Conceptually, I think Joanna is right. In practice, I've found that using > the class as a singleton doesn't always serve the purpose -- though I can > never remember the usage case that's a problem. I think it's something like > trying to use a class object as a 'didEnd' selector delegate, where you end > up wanting encapsulated instance variables. I won't insist that my use of singletons is always justified. I'll merely say it doesn't hurt to use them in the way that I most often use them, namely, as providers of specific services (locale utils, reachability, core data, and so on). At least that's my experience so far. > OTOH, I'm not sure I understand your objection as expressed above. You can of > course subclass a class (i.e. override class methods). Having to search for > the class name seems no different from the case where you change the name of > your singleton-getter-method. But let's not get side-tracked into that ... My objection comes in the context of already having a code base in place that uses a class object. If a need to subclassing that class arises, then the code base may need a significant amount of change. Writing the code base to begin with using a singleton approach reduces this problem. > 2. FWIW, I'm generally with Kyle and others who are suggesting that trying to > implement forced, generalized singleton-ness may be a practical un-necessity. Fair enough, but I do find clutter in classes to be distracting to the point of making it difficult to understand what the classes' responsibilities are. I've worked on projects where other people have made the app delegate responsible for everything and the kitchen sink. It's one thing to have a few core data stack methods in the app delegate; it's another to do a lot of one's core data tasks in the app delegate. Personally, I prefer to move all of that to a class whose sole responsibility is to manage core data tasks. > A while back, I asked on this list whether a singleton is an object that > there *is* only one of, or it's an object that there *can be* only one of. > The answer, from someone whose opinion I respect (and who is almost always > right) was "is", not "can be". > > So the issue being discussed in this thread is not how to create a singleton, > but how to prevent the creation of a second object of the class, which is a > different matter. To be fair, the issue was originally "is there something else in this code that I'm missing". The thread has since turned into why/when it is appropriate, or not, to use a singleton. > I understand that you're implementing forced, generalized singleton-ness as a > matter of interest as much as anything else, and I'm not saying don't do it, > but I am asking how it protects you ... from who? what? ... more effectively > than the low-tech solution outlined above. The honest answer is that I don't know (how it protects me, from who (or whom?) or what), but I won't find out if I don't explore the issue, will I? :) > 3. This thread really isn't about singletons at all. Looking back at your > original post, it's really about thread-safe creation of shared objects: That's certainly a big component of my original question, yes, but I also had an interest in seeing that question answered in the specific context of implementing a singleton. > On Apr 16, 2011, at 20:04, WT wrote: > >> Among other things, I wanted to replace my usage of @synchronized >> singletons, and dispatch_once() seemed the perfect mechanism for that. > > > In that context, my question is: what's wrong with @synchronized? After all, > it can't be a performance issue when it only happens once per singleton > class. Why is @synchronized an imperfect mechanism? It probably isn't an imperfect mechanism and is probably fine from a performance point of view. And, yes, attempting to replace that mechanism with dispatch_once() may be a case of premature optimization. I won't deny any of that. At the end of the day, the most honest answer I can give is that I wanted to explore dispatch_once() and thought that doing so in the context of implementing singletons would be a good learning experience. This thread and links to some blogs on the issue have given me much to think about. I may yet come to change my habit of seeing singletons where they don't need to be seen, because of this discussion. WT ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Proper way to create a singleton without @synchronized ?
On Apr 18, 2011, at 5:05 AM, Joanna Carter wrote: > Yes; after the first few projects, based on the default Core Data project > template, I started to realise that this (separating out the Core Data stack) > was an excellent case for a singleton/static class. > > Can someone tell me if it is just a matter of adding/modifying class files in > the templates folder to make this happen every time? > > Joanna Yes, it's as simple as that, although you might want to move your changed templates to where your changes won't disappear after the next XCode install. For XCode 3.x, that's ~/Library/Application Support/Developer/Shared/XCode/File Templates ~/Library/Application Support/Developer/Shared/XCode/Project Templates and so on, after which your custom templates will be visible as separate entries in the "new project" and "new file" windows. XCode 4 doesn't seem to support custom templates at the moment. WT___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
(iOS) strange animation bug
Hello list, so I have this little setup where, upon a user's action, a view ('notes' view, blue bg) slides down from under another view ('masking' view, black bg) while some buttons appear inside the masking view (btns 0,1,2,3). Buttons 1,2,3 start on top of btn 0 and spread out, while fading in (btn 0 stays put, and btn 2 doesn't fade). If the user then chooses to hide the notes view, it will slide back up under the masking view while buttons 1,2,3 move back on top of btn 0, fading out (resulting in btn 2 appearing where btn 0 is, but at full opacity). <> My problem is that the buttons aren't moving back on top of btn 0, fading out. Rather, they simply get hidden (or their alphas are set to 0.0), *before* the sliding animation takes place. Actually, that's true only for btns 0,1,3. Btn 2 does move as expected (it's the one that shouldn't fade). I've stared at my code for quite some time now and can't see what's wrong, so I wrote a test app that shows the problem. There is also a table view (orange bg) that should (and does) resize as the notes view slides in and out but it doesn't participate in anything interesting in the code below, so I replaced it with a regular view. The problem happens when the app is compiled with either XCode 3.2.6 or 4.x, under iOS 4.3, on Snow Leopard 10.6.8. The test app can be found here: (74 Kb) http://www.restlessbrain.com/CocoaDev/AnimBug.zip and the relevant code is: [ apologies for the uninspired variable names and the awful-looking UI - trying to protect the innocent, so to speak :) ] - (void) viewWillAppear: (BOOL) animated; { [super viewWillAppear: animated]; [self showNotesView: NO animated: NO]; } - (IBAction) toggleNote; { [self showNotesView: ! notesVisible animated: YES]; } - (void) showNotesView: (BOOL) show animated: (BOOL) animated; { notesVisible = show; self.view.userInteractionEnabled = NO; self.btn3.alpha = 0.0f; self.btn1.alpha = 0.0f; self.btn0.alpha = 0.0f; self.btn3.enabled = NO; if (! animated) { [self showNotesView: show]; self.view.userInteractionEnabled = YES; } else { [UIView animateWithDuration: 3.0f animations: ^(void) { [self showNotesView: show]; } completion: ^(BOOL finished) { self.view.userInteractionEnabled = YES; } ]; } } - (void) showNotesView: (BOOL) show; { CGFloat maskingViewBottom = self.maskingView.frame.origin.y + self.maskingView.frame.size.height; CGFloat toolBarTop = self.toolbar.frame.origin.y; CGRect notesFrame = self.notes.frame; CGRect tableFrame = self.table.frame; if (show) { notesFrame.origin.y = maskingViewBottom; self.notes.frame = notesFrame; tableFrame.origin.y = maskingViewBottom + notesFrame.size.height + 10.0f; tableFrame.size.height = toolBarTop - tableFrame.origin.y; self.table.frame = tableFrame; CGPoint center = self.btn0.center; center.x -= 37.0f; self.btn1.center = center; center.y -= 41.0f; self.btn2.center = center; center.x += 37.0f; self.btn3.center = center; self.btn3.alpha = 1.0f; self.btn1.alpha = 1.0f; self.btn0.alpha = 1.0f; } else { self.btn3.center = self.btn0.center; self.btn1.center = self.btn0.center; self.btn2.center = self.btn0.center; self.btn3.alpha = 0.0f; self.btn1.alpha = 0.0f; self.btn0.alpha = 0.0f; notesFrame.origin.y = maskingViewBottom - notesFrame.size.height; self.notes.frame = notesFrame; tableFrame.origin.y = maskingViewBottom; tableFrame.size.height = toolBarTop - maskingViewBottom; self.table.frame = tableFrame; } } More specifically, you can ignore the sliding in and out of the notes and table views, and focus only on the button motion/fading: if (show) { CGPoint center = self.btn0.center; center.x -= 37.0f; self.btn1.center = center; center.y -= 41.0f; self.btn2.center = center; center.x += 37.0f; self.btn3.center = center; self.btn3.alpha = 1.0f; self.btn1.alpha = 1.0f; self.btn0.alpha = 1.0f; } else { self.btn3.center = self.btn0.center; self.btn1.center = self.btn0.center; self.btn2.center = self.btn0.center; self.btn3.alpha = 0.0f; self.btn1.alpha = 0.0f; self.btn0.alpha = 0.0f; } The YES branch executes as expected but the NO branch executes as if the alphas get cleared immediately, even though the entire thing appears inside an animation block. This is really simple stuff, and I can't see what may be wrong with it. Any help is appreciate
[Solved] (iOS) strange animation bug
Duh... I set the button alphas to 0 before animating them back. I can't believe I looked at those lines of code so many times and didn't realize what the problem was. Simply removing those 3 lines makes the code work as intended. Sorry about the noise. WT - (void) showNotesView: (BOOL) show animated: (BOOL) animated; { notesVisible = show; self.view.userInteractionEnabled = NO; self.btn3.alpha = 0.0f; // These 3 lines are fine (but not needed) when self.btn1.alpha = 0.0f; // show == YES but cause the problem I was seeing self.btn0.alpha = 0.0f; // when show == NO self.btn3.enabled = NO; if (! animated) { [self showNotesView: show]; self.view.userInteractionEnabled = YES; } else { [UIView animateWithDuration: 3.0f animations: ^(void) { [self showNotesView: show]; } completion: ^(BOOL finished) { self.view.userInteractionEnabled = YES; } ]; } } ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Augmented Reality App
Hi Paul, just yesterday I came across the following, which is very simple but might still be useful to your team: http://www.raywenderlich.com/3997/introduction-to-augmented-reality-on-the-iphone Hope that helps. WT On 11 Jul 2011, at 23:03, Paul Scott wrote: > Anyone that has done an app relating to Augmented Reality that can give > members of my team a short primer on Augmented Reality and might be > interested in being hired to build an app? Contact me if you have any > interest. > > Thanks, > > > > > Paul "Mac Guy" Scott > > > > > > Web > http://www.macguy.info > > Twitter > http://twitter.com/paulmacguyscott > > Blog > http://blog.macguy.info ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Cocoaheads?
On 14 Jul 2011, at 01:23, William Squires wrote: > Sorry about the post - if there's an appropriate Apple list for info on > Cocoaheads clubs is/are, please direct me there. I'm interested to see if > there's one here in San Antonio, TX, USA. Google is your friend. Search for "cocoaheads" (sans quotes) and it's the very top result. ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Help needed with setting autoresizing masks
Hello list, I've been scratching my head for a few hours already trying to get the autoresizing masks set correctly for the following situation, with no luck, and would greatly appreciate some help. I have a view containing two labels, labelA and labelB, horizontally laid out in sequence, like this: |..|labelA||labelB|..| The outermost bars represent the edges of the view, and the labels are inset by a fixed amount. The dots represent empty space. When the user taps on the view, both labels slide inwards to provide space for two buttons, so the final position should look like this: |..|btnA|..|labelA||LabelB|..|btnB|..| I've already gotten all the code working correctly (I checked the math in general and with specific examples), the animated sliding works, and it's all great - except that labelB is intersecting btnB. At first I thought this was an error in my code or in the math, but that isn't it. The problem is with the autoresizing masks. I verified that by NOT changing the position of labelB in code and noticing that it still moves. Of course, I could hack a solution by figuring out the extra horizontal displacement and subtracting that amount from the final x coordinate of labelB, but I'd rather get it right just by setting the right autoresizing masks. I also tried turning off the "autoresize subviews" option in IB for the container view (and all 4 elements, not that that should matter), in the hopes that that would work since I compute the correct coordinates for all elements myself. Yet, it still didn't work. You can see some pictures of the situation here: http://www.restlessbrain.com/auto_res_mask/before_tap.png http://www.restlessbrain.com/auto_res_mask/after_tap.png http://www.restlessbrain.com/auto_res_mask/cell_on_IB.png http://www.restlessbrain.com/auto_res_mask/mask.png The mask picture applies to all labels on the other pictures. Any help is appreciated. Thanks! Wagner ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Help needed with setting autoresizing masks
Hi Seth, thanks for answering to my call for help. You make a good point. Perhaps it is a problem with my code after all. However, not updating the label positions still causes them to move and if I am not moving them, someone else is. Anyhow, I created a sample project that still shows the problem. It can be downloaded from: http://www.restlessbrain.com/auto_res_mask/ARMaskIssue.zip Thanks for taking a shot at it. Wagner On May 29, 2009, at 11:34 PM, Seth Willits wrote: On May 29, 2009, at 1:38 PM, WT wrote: I also tried turning off the "autoresize subviews" option in IB for the container view (and all 4 elements, not that that should matter), in the hopes that that would work since I compute the correct coordinates for all elements myself. Yet, it still didn't work. Which seems to confirm that it is *not* a problem with the autoresizing masks. (And if the containing view is not resizing, then how could it be?) I would say some pasted code is in order, here. Can you replicate the problem in a small sample project? -- Seth Willits ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
[SOLVED} Help needed with setting autoresizing masks
It turns out that everything works as is if the table view has the "plain" style, rather than the "grouped" style. So, the problem is really that I didn't account for the fact that a grouped cell will be horizontally shrunk if the custom cell in the nib file has the full screen width. This may in fact cause autoresizing issues (though it didn't in my case because, as it happens, I had the correct autoresizing masks set in the first place) and also my code was indeed broken in that it didn't account for the correct cell content width. It worked for plain table views because their cells have the full screen width for their content views. The solution, besides making sure that the autoresizing masks are set correctly, is to do some extra horizontal shifting in the case of grouped cells but, for efficiency reasons, we need to know whether a cell is grouped or not early on, rather than when the cell is actually drawn. Otherwise, one would have to implement the delegate method - tableView: willDisplayCell: forRowAtIndexPath: and do all the math there, much of which would be the same for every cell. So, I added a boolean ivar 'inPlainTableView' to my custom cell class and I set it when the cell is handed to the table view, in the method - tableView: cellForRowAtIndexPath:, since I can ascertain right there and then what kind of table view I've got. That way, the cell gets a chance to do much of the math at load time, caching everything it needs for the time to draw the cell. The actual extra horizontal shift is simply the x coordinate of the cell's 'contentView' in its parent view. Actually, it's *twice* that for the items that are laid out on the right side of the cell and which move inward. So, adding if (! self.inPlainTableView) { CGFloat extraHorizShift = 2 * self.contentView.frame.origin.x; targetDateLabelFrame.origin.x -= extraHorizShift; targetTimeLabelFrame.origin.x -= extraHorizShift; } at the appropriate time, is pretty much all that needed to be done in my particular case. The solved sample project, in case anyone is interested, can be found here: http://www.restlessbrain.com/auto_res_mask/ARMaskIssue_solution.zip Wagner Hi Seth, thanks for answering to my call for help. You make a good point. Perhaps it is a problem with my code after all. However, not updating the label positions still causes them to move and if I am not moving them, someone else is. Anyhow, I created a sample project that still shows the problem. It can be downloaded from: http://www.restlessbrain.com/auto_res_mask/ARMaskIssue.zip Thanks for taking a shot at it. Wagner On May 29, 2009, at 11:34 PM, Seth Willits wrote: On May 29, 2009, at 1:38 PM, WT wrote: I also tried turning off the "autoresize subviews" option in IB for the container view (and all 4 elements, not that that should matter), in the hopes that that would work since I compute the correct coordinates for all elements myself. Yet, it still didn't work. Which seems to confirm that it is *not* a problem with the autoresizing masks. (And if the containing view is not resizing, then how could it be?) I would say some pasted code is in order, here. Can you replicate the problem in a small sample project? -- Seth Willits ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Message from view to viewController
On May 30, 2009, at 4:40 PM, Pierre Berloquin wrote: [theViewController vagTouchesBegan:self]; QED There's still a warning that the view controller may not respond. But it works seamlessly. Can I get rid of the warning? Yes, by declaring the method -vagTouchesBegan: in the header file of your view controller class. Something to be cautious about when storing in the view a pointer to its view controller is that you may end up creating a retain cycle, since the view controller already retains its view. I would recommend that you read the documentation on memory management to make sure you don't create unnecessary problems for yourself. Wagner ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Message from view to viewController
On May 30, 2009, at 5:43 PM, Pierre Berloquin wrote: Declaring in .h -(void)vagTouchesBegan:(id)sender; was my first impulse. But that's not enough. It's not clear from your two posts which method you're getting a warning for. I thought it was for the -vagTouchesBegan method, but you claim it's not. Please post the actual warning that you get from XCode. About the memory problem, I suppose I should receive touchesBegan in the controller and sort out what I get ? No, that's not what I was referring to. I was referring to the fact that if an object of class A retains an object of class B and that same object of class B also retains the object of class A which retains it, then you have what's called a retain cycle. That may cause you trouble if you're not careful. The view controller already retains its view, so if you're passing the view controller object to the view object for it to keep, then the view object should NOT retain that view controller object. If what I just said isn't completely clear to you, you should read http://devworld.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html If that document is still a bit obscure, then you should search the web for more accessible explanations. For instance, http://stackoverflow.com/questions/791322/retain-cycles-why-is-that-such-a-bad-thing Note that it *is* ok for the view object to have a pointer to its view controller. All I'm saying is that you should avoid retaining the view controller in its view. Thus, instead of - (void) setViewController: (UIViewController*) vcontroller { [viewController release]; viewController = [vcontroller retain]; } (which is the typical setter for objects) you should have - (void) setViewController: (UIViewController*) vcontroller { viewController = vcontroller; // Note: no release and no retain } (atypical for objects, but necessary in this case to avoid a retain cycle). Or, if you prefer to use properties, instead of @property (readwrite, nonatomic, retain) UIViewController* viewController; you should use @property (readwrite, nonatomic, assign) UIViewController* viewController; Wagner 2009/5/30 WT On May 30, 2009, at 4:40 PM, Pierre Berloquin wrote: [theViewController vagTouchesBegan:self]; QED There's still a warning that the view controller may not respond. But it works seamlessly. Can I get rid of the warning? Yes, by declaring the method -vagTouchesBegan: in the header file of your view controller class. Something to be cautious about when storing in the view a pointer to its view controller is that you may end up creating a retain cycle, since the view controller already retains its view. I would recommend that you read the documentation on memory management to make sure you don't create unnecessary problems for yourself. Wagner ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Message from view to viewController
On May 31, 2009, at 8:04 AM, Pierre Berloquin wrote: Also I follow your advice about retaining loopholes and use -(void)setViewController:(UIViewController *) vc{ theViewController = vc; } So the warning remains puzzling. Note that it's displayed on the sub view .m page only, after the call line, not after the mention "Succeeded". I think you're under the impression that the recommendation to avoid retain cycles is somehow related to the warning you received. It is not. I made that recommendation as a general statement since you're doing something that could very easily cause retain cycles (namely, having a view store a pointer to its view controller). On May 31, 2009, at 11:30 AM, Pierre Berloquin wrote: I think I solved the warning problem. I suspected my folder logic was wrong so I cleaned it up, taking all class files from the project and adding them back one by one. And it works fine, no warning anywhere !I had a duplicate controller I had created by mistake and I thought I had gotten rid of. Ok, that might be it. If it works now, great. Thanks Welcome. Wagner ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: End Of Method Releasing Order?
I don't think so. Releasing objects merely decreases their retain count. It's up to the Obj-C runtime system to figure out in what order to actually free the memory allocated for those objects. In other words, we are not the ones deciding how and when to deallocate memory allocated for objects. We merely indicate to the runtime system that we're no longer interested in a given object at a given point in the program runtime execution flow. What happens to the object after that is not up to us. On Jun 2, 2009, at 2:46 AM, Chunk 1978 wrote: does it matter which order objects are released at the end of a method? example: ... at the end i'm finished with archiver, data and fourLines, but does it matter in this case which one i release first? ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: re-making connections with a different controller
Hi Stephen, one approach that I have successfully employed several times when having to do a substantial amount of dreadful and error-prone mechanical work on xib files, of the kind you're talking about, is to use a text-editor and do a search and replace on the contents of the xib file. This works because xib files are xml files. So, in your particular case, I'd set up ONE tab then copy all of its contents to all other 9 tabs, then save and close the xib file. Then I'd open the same xib file in a text editor (my favorite is BBEdit) and do a search/replace for the controller name. You can even do a grep search and replace so you won't have to do the same operation 9 times, but only once. If you haven't done this before, though, I strongly recommend that you keep a backup of your xib file prior to messing with it inside the text editor, because it's easy to muck things up and end up with a corrupted xib file. Good luck. Wagner On Jun 10, 2009, at 1:15 AM, Stephen Blinkhorn wrote: Hi all, Imagine I have an NSTabView with 10 tabs that all contain the same collection of controls. The only difference is that each control's action/outlet is connected to a different controller object (of the same class type). Is it possible to select a whole tab of controls, copy them to the next tab and somehow change all the connections to and from Controller1 so that they now connect to Controller2,3,4,5,6 etc without having to do 300 CTRL drags. Perhaps this illustrates an underlying fundamental problem with the structure of my app but I don't want to know about that right now :) Well, ok, maybe I do... Thanks, Stephen ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: dumb question
I have the following in a project of mine, in a file Constants.h, which I import as needed from other source files: #define kAppFrame ([UIScreen mainScreen].applicationFrame) #define kScreenWidth([UIScreen mainScreen].bounds.size.width) #define kScreenHeight ([UIScreen mainScreen].bounds.size.height) #define kStatusBarHeight(kScreenHeight - kAppFrame.size.height) So, in your case, why not something like the following? #define kScreenBounds ([[UIScreen mainScreen] bounds]) On Jun 12, 2009, at 12:36 PM, Chunk 1978 wrote: maybe this coffee hasn't kicked in yet and undoubtedly there is a simple solution, but i'm trying unsuccessfully to refactor some code, and i'd like to set the following as a static or define instead of having it written several times in several methods -=-=-=- CGRect fullScreenRect = [[UIScreen mainScreen] bounds]; -=-=-=- how can i do that? ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Coming up with ideas
On Jun 13, 2009, at 4:36 AM, Graham Cox wrote: On 13/06/2009, at 12:30 PM, Development wrote: Hey, how do you guys come up with ideas for new programs? I'm going nuts trying to figure out what type of application I should make. I wish I had your problem ;-) I come up with ideas for new apps several times a week. I'm going nuts trying to figure out how I'll ever find time to implement them without dozens of developers! --Graham Hi Graham, care to share some of them? I'm sure lots of people like the OP and myself, who are not as prolific in coming up with ideas as you are, would be happy to take a shot at some of your ideas. Wagner ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Coming up with ideas
Hi Graham, care to share some of them? I'm sure lots of people like the OP and myself, who are not as prolific in coming up with ideas as you are, would be happy to take a shot at some of your ideas. Wagner Well, most of them reflect two things: a) my interests and b) the lack of certain categories of affordable software on the Mac. So these aren't necessarily original ideas, but I wish there were: a) really good CAD software that was in a hobbyists price-range but was of professional quality and a true OSX app, not a crappy port or half-baked shareware effort b) ditto PCB design software c) ditto electronic simulation software (both digital and analogue) d) ditto mechanical/kinematics design and simulation software In recent years the quality of shareware or low-cost apps in certain sectors such as drawing and painting has improved dramatically. I'd like to see the same ethos spread to some of these other areas, but of course such apps are far from trivial. On d) if anyone can point me to a decent open-source kinematics library I'm all ears... --Graham Nice ideas, but I think they're far too challenging for the amount of Cocoa programming experience I have, so I won't be taking any shots at them any time soon. :) This discussion reminds me, by the way, of an idea of my own that I've had nearly 20 years ago, back when I was a particle physics grad student. Back then, I wanted to write an application that would draw all Feynman diagrams of a particular kind for a particular interaction Lagrangean. You'd specify the interaction vertices, the incoming and outgoing lines, and the number of loops, and the application would draw all diagrams with those properties. I also wanted the application to output (in LaTeX-typeset form) the associated Feynman integral for each diagram it generated. Now, back then I had the math and physics understanding necessary to write such an application, but not the programming experience. Today, I'm much better prepared on the programming end of it, but I've since forgotten some of the math and physics knowledge required. Moreover, it's still a daunting task, I think. So, if anyone else wants to give it a shot, please do. I'm sure it would be very useful to a lot of particle physics students and professionals out there. Wagner ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
[iPhone] Strange behavior with modal view controllers
Hi there, I'll ask the question first, then I'll explain why I'm asking it. Is there any known reason whatsoever why presentModalViewController would do absolutely nothing? In an iPhone game app I'm working on, I have a tab-bar with 5 items, 2 of which are managed by the SettingsViewController and the GameViewController, respectively. The player can freely switch between any two views by tapping the appropriate button on the tab-bar, *except* that - once the game view has been switched into - the player can only switch between the game view and the settings view. This allows the player to change settings within the app, but without being in a game, as well as while playing a game, and prevents the player from accessing other views that are not supposed to be accessible during game play. In order to implement this, I use the tab-bar delegate method - tabBarController: shouldSelectViewController: to detect when the player is attempting to switch to the game view, make the game view controller the active one (directly, not through the tab-bar controller), release the tab-bar controller, and then return NO: - (BOOL) tabBarController: (UITabBarController*) tab_bar_controller shouldSelectViewController: (UIViewController*) view_controller { BaseViewController* curVC = (BaseViewController*) tabBarController.selectedViewController; BaseViewController* newVC = (BaseViewController*) view_controller; NSUInteger kindOfCurVC = curVC.viewControllerKind; NSUInteger kindOfNewVC = newVC.viewControllerKind; if (kindOfNewVC == kindOfCurVC) { // Since the tab-bar view responds to taps on an already // selected tab-bar item, and we don't want to do work that // has already been done, we should return NO in this case. return NO; } else if (kindOfNewVC == kViewControllerKindGame) { // Switching to the game view. Return NO because // the active view controller will change directly // to the game view controller and the tab-bar controller // will never get a chance to switch to the game view. [tabBarController.view removeFromSuperview]; [window addSubview: gameViewController.view]; [tabBarController release]; tabBarController = nil; return NO; } else { // Switching to a view other than the game view. return YES; } } At this point, it's as if I never had a tab-bar controller. Of course, I need to have retained both the SettingsViewController and the GameViewController, which I did when I grabbed them from the tab-bar view controllers array back in the -applicationDidFinishLaunching: method. So, now, when I want to switch between the game and settings views, I use a modal view controller scheme, with the SettingsViewController being the modal partner of the GameViewController. I also have a button on the settings view, that is hidden when the settings view controller is being managed by the tab-bar but visible when not. The button's action triggers the dismissal of the modal behavior, returning to the game view. Everything works great, except for one thing: the call [gameViewController presentModalViewController: settingsViewController animated: YES]; does absolutely nothing! Moreover, I've verified that, after that call, gameViewController.modalViewController is nil. The AppDelegate method - (void) switchFromGameToSettings { NSLog(@"AppDelegate: -switchFromGameToSettings"); [gameViewController presentModalViewController: settingsViewController animated: YES]; NSLog(@"settingsViewController = %@", settingsViewController); NSLog(@"gameViewController = %@", gameViewController); NSLog(@"gameViewController.modalViewController = %@", gameViewController.modalViewController); // Tell the settings view controller that it is now in-game. settingsViewController.inGame = YES; } (triggered by a tap on the appropriate button on the game view, which triggers an action method in the game view controller, which calls - switchFromGameToSettings on the application delegate) results in: AppDelegate: -switchFromGameToSettings settingsViewController = gameViewController = gameViewController.modalViewController = (null) My first thought was that perhaps either one or both of the view controllers might still be tied up with the tab-bar controller, somehow, even though I've killed the tab-bar by this point. So, I tried a little hack where I create a fresh new pair of view controllers just prior to the presentModalViewController call, and now things do work correctly. A little more investigation then revealed that I don't need to have a fresh new SettingsViewController object, ie, the one I grabbed from the tab-bar works just fine. The problem is then with the GameViewController object. Now, since the game view does appear on
[iPhone] (follow-up) Strange behavior with modal view controllers
Hello again, I've since created a small project that shows exactly the problem I described. It's a 32 Kb download, found here: http://www.restlessbrain.com/ModalVCTrouble.zip For this small project, I stripped off all animations and any irrelevant code, so it's the smallest project I can come up with that presents the problem I described. I'd greatly appreciate if someone could take a look at it and help me figure out what's wrong. Incidentally, you'll also notice a problem with the settings view resizing incorrectly, but that's irrelevant for the purpose at hand and it's a matter of setting the correct autoresizing masks anyway. Thanks in advance. Wagner ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Arranging NSStrings in a Table column
Use 3 labels or text-fields, align them in your table view cell using Interface Builder, set the appropriate justification (left, right, or center), and then use a couple of lines of code to set their text values with the actual strings you have. Wagner On Jun 17, 2009, at 3:13 PM, Arun wrote: Hi All, I have 3 NSStrings How can i arrange mutiple strings with proper allignment in a table column as below. Any ideas? | | | | | | | | | | | | - Thanks Arun KA ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: [iPhone] (SOLVED) Strange behavior with modal view controllers
Hi Michael, thanks for replying to my message. I'm not 100% certain, but I believe this delegate method is new in iPhone OS 3.0 (couldn't find it in the 2.2.1 docs). The project you put together also specifies the iPhone 3.0 SDK. I don't believe it is kosher to speak of these things on the list at this point, but we can easily switch to using the iPhone OS 2.2.1 SDK and substitute the -tabBarController:didSelectViewController: delegate method in their place. Oops... indeed. My apologies. I'll remove the 3.0 sample project as soon as I finish this message. I suspect that the problem is that your view controllers (Game and Settings) are left in a "confused" state, with their parent view controller still referring to the removed and released UITabBarController. Since the parentViewController and tabBarController properties of the UIViewController are read-only, you can attack this from the other end by removing them from the UITabBarController's list of viewControllers before releasing it. Like so: - (void)tabBarController:(UITabBarController *)tab_bar_controller didSelectViewController:(UIViewController *)newVC { if (newVC == gameViewController) { [tabBarController.view removeFromSuperview]; [window addSubview: gameViewController.view]; NSMutableArray *tabViewCtlrs = [[tabBarController viewControllers] mutableCopy]; [tabViewCtlrs removeObject:gameViewController]; [tabViewCtlrs removeObject:settingsViewController]; [tabBarController setViewControllers:tabViewCtlrs]; [tabViewCtlrs release]; tabViewCtlrs = nil; [tabBarController release]; tabBarController = nil; } } In my modified copy of your sample project, this change seems to do the trick. Yes, on further investigation, I noticed that the settings view controller had its parentViewController set to the tab-bar controller instance, which was still alive and well. Clearly, an UIViewController instance retains its parent controller. Oddly enough, there doesn't seem to be a direct way to detach a former modal view controller from its parent. I assumed that calling -presentModalViewControler would reset the properties accordingly, but obviously that's not the case. If only parentController was writable... Anyway, there's a simpler solution than yours, though along the same lines. Since I'm going to kill the tab-bar controller anyway, I can simply set its viewControllers property to nil before releasing the tab-bar controller. Thanks again for your help. Wagner ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Group CGAffineTransform Animations?
On Jun 17, 2009, at 4:37 PM, Graham Cox wrote: It's fair to say that transforms can be a bit unintuitive - you expect them to perform the operations in the order you set. In fact, the reverse order is what it will actually do. (The explanation for this lies in the maths, but it sounds like you're not interested in that, in which case this might be a struggle). For people with a background closer to programming and farther from math, it might be easier to think of matrix multiplication as a stack (the LIFO kind of data structure). What you write last is what gets done first when it comes to using matrices as operations on geometrical objects. So, the result of applying ABC to an object o (where A, B, and C are matrices) is that first C is applied to o, then B is applied to the result of that, then A is applied to the result of *that*. In reality, behind the curtains, it may be and often is the case that A, B, and C get multiplied together first and then the result of that is applied to o, but conceptually you can think of it as I described. Wagner ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Group CGAffineTransform Animations?
On Jun 17, 2009, at 9:10 PM, Chunk 1978 wrote: ... perhaps there's a way to set the transforming object's origin to it's center some how? i could work with that... The problem is a more subtle one than simply a question of what order in which to perform the transforms. What's happening is that as your cube scales in size, its origin changes and that screws up the translation. I created a sample project that moves a small image from (0,0) to the center of the screen, while rotating it by 90 degrees and scaling it by a factor of 2 in each direction. You can download it from here: http://www.restlessbrain.com/AffineTs.zip Or you can simply look at the code below. The key lines are: CGAffineTransform transform; transform = CGAffineTransformMakeScale(kScaleX, kScaleY); transform = CGAffineTransformTranslate(transform, targetCenter.x / kScaleX, targetCenter.y / kScaleY); transform = CGAffineTransformRotate(transform, DEGS_TO_RADS(90)); Note how you have to divide the target position coordinates by the same scale factor you're changing the size of the object you're applying the transform to. The constants and macro are simply: #define kAnimDuration 2.0 #define kScaleX 2.0 #define kScaleY 2.0 #define DEGS_TO_RADS(DEGS) (DEGS * M_PI / 180.0) - (IBAction) actionApplyTransform: (id) sender { // NSLog(@"ViewController: -actionApplyTransform:"); CGRect screenBounds = [[UIScreen mainScreen] bounds]; CGPoint screenCenter = { CGRectGetMidX(screenBounds), CGRectGetMidY(screenBounds) }; CGRect imgBounds = imgView.bounds; CGPoint imgCenter = { CGRectGetMidX(imgBounds), CGRectGetMidY(imgBounds) }; // The image's origin is not at its center, so when // targetting a destination point, we must account // for that. CGPoint targetCenter; targetCenter.x = screenCenter.x - imgCenter.x; targetCenter.y = screenCenter.y - imgCenter.y; [UIView beginAnimations: nil context: NULL]; [UIView setAnimationDuration: kAnimDuration]; [UIView setAnimationDelegate: self]; [UIView setAnimationCurve: UIViewAnimationCurveEaseInOut]; CGAffineTransform transform; transform = CGAffineTransformMakeScale(kScaleX, kScaleY); // As the image scales in size, its origin changes. // Thus, we have to scale the destination point by // same scale factor, but "in reverse". transform = CGAffineTransformTranslate(transform, targetCenter.x / kScaleX, targetCenter.y / kScaleY); transform = CGAffineTransformRotate(transform, DEGS_TO_RADS(90)); imgView.transform = transform; [UIView commitAnimations]; } // Wagner ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Group CGAffineTransform Animations?
On Jun 17, 2009, at 10:50 PM, David Duncan wrote: On Jun 17, 2009, at 7:21 AM, Chunk 1978 wrote: premiss: a red cube, 50 width x 50 height, located at {0,0}. i want to scale the cute 2 times it's width and height, move it to the center of the screen, and rotate it 90ยบ In general you will have a better understanding of what is going on in your application if you stick to using transforms to scale & rotate your views, rather than to move your views (i.e. translation). It is fully supported to use translation, and necessary for certain types of animation, but if your goal is to move a view to the center of the screen (for example) then setting the view's center to the center of the screen is a saner approach than using the transform matrix to do it. Hi David, my understanding was that the OP wanted to do all three operations concurrently. Of course, if he wants simply to move, then scale, and then rotate, there are easier ways to accomplish that than to use transforms. Wagner___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Group CGAffineTransform Animations?
On Jun 17, 2009, at 10:40 PM, Erik Buck wrote: Only a little bit of math is neccessary to use affine transforms. A lot of math is needed for general 3D programming, but let's ignore that for now. My third grader was tought about associative and communitive math operstions. Some matrix operations are associative and some are communitive. That's why the order of operations matters. To scale and rotate a square without moving the center of the square, do the following: A) translate to the center of the square making that position the new origin for scaling and rotation. B) Scale the coordinate system. C) Rotate the coordinate system D) Translate back to the original origin F) Draw the square It's not so hard typed in web-mail: CGAffineTransform TransformToScaleAndRotateAboutCenterOfSquare(NSRect someSquare) { CGAffineTransform transform = CGAffineTransformMakeTranslation( NSMidX(someSquare), NSMidY(someSquare)); transform = CGAffineTransformScale (transform, 2.0f, 2.0f); transform = CGAffineTransformRotate(transform, DEGS_TO_RADS(90)); transform = CGAffineTransformTranslate(transform, - NSMidX(someSquare), -NSMidY(someSquare)); return transform; } You're absolutely correct in general, but - if I'm not mistaken - CGAffineTransform rotations and scalings already do their thing with respect to the center of the view they're being applied to. In fact, I tested that before writing my solution to the OP's problem. And that is indeed the source of the problem. Rotations and scalings, as implemented by CGAffineTransform, are with respect to the view's center but translations are with respect to the view's origin. Therefore, if you scale while you translate, the view's origin changes and the translation is no longer being applied with the correct offset. To be honest, I'm a bit surprised that CGAffineTransform rotations and scalings are already defined with respect to the center of the view. There's still a part of my brain that thinks that that isn't true, but my tests indicated otherwise. Wagner ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Group CGAffineTransform Animations?
On Jun 17, 2009, at 11:28 PM, David Duncan wrote: On Jun 17, 2009, at 1:58 PM, WT wrote: my understanding was that the OP wanted to do all three operations concurrently. Of course, if he wants simply to move, then scale, and then rotate, there are easier ways to accomplish that than to use transforms. You can set the center & transform of a view within the same animation block and both animations will occur concurrently. Yes, of course! Duh... in my haste to answer, I misunderstood what you said in your previous post. Your comment provides the clearest and cleanest solution: CGRect screenBounds = [[UIScreen mainScreen] bounds]; CGPoint screenCenter = { CGRectGetMidX(screenBounds), CGRectGetMidY(screenBounds) }; [UIView beginAnimations: nil context: NULL]; [UIView setAnimationDuration: kAnimDuration]; [UIView setAnimationDelegate: self]; [UIView setAnimationCurve: UIViewAnimationCurveEaseInOut]; CGAffineTransform transform; transform = CGAffineTransformMakeScale(kScaleX, kScaleY); transform = CGAffineTransformRotate(transform, DEGS_TO_RADS(kAngleInDegrees)); imgView.transform = transform; imgView.center = screenCenter; [UIView commitAnimations]; For future reference and for the benefit of the OP, I've now updated my sample project. Wagner ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com
Re: Group CGAffineTransform Animations?
On Jun 17, 2009, at 11:53 PM, Erik Buck wrote: My third grader was taught about associative and commutative math operations. Some matrix operations are associative and some are commutative. That's why the order of operations matters. Just in case: I didn't mean to imply that even third graders should understand matrix math. They do in Star Trek The Next Generation. Or maybe it was calculus. You're absolutely correct in general, but - if I'm not mistaken - CGAffineTransform rotations and scalings already do their thing with respect to the center of the view they're being applied to. In fact, I tested that before writing my solution to the OP's problem. And that is indeed the source of the problem. Rotations and scalings, as implemented by CGAffineTransform, are with respect to the view's center but translations are with respect to the view's origin. Therefore, if you scale while you translate, the view's origin changes and the translation is no longer being applied with the correct offset. To be honest, I'm a bit surprised that CGAffineTransform rotations and scalings are already defined with respect to the center of the view. There's still a part of my brain that thinks that that isn't true, but my tests indicated otherwise. Wagner OK. I will have to try this at home. If you create a CGAffineTransform as I did and then use [myUIView setTransform:myTransform], how can a UIView know that part of my transform matrix applies one way and another part applies another way ? I think it is mathematically impossible unless the view is pulling components out of the transform matrix rather than just concatenating the matrix I supply with whatever matrix it's superview uses. If it pulls components out of the transform matrix, it is not a proper affine transform (because shear and skew and some degenerate cases will not work) and all of the functions are misnamed. Your objections are precisely the reasons why some part of my brain is screaming at the rest of it for publicly making a statement which it believes to be incorrect. It may sound strange, but I'll be happy to be proven wrong on this one. Wagner ___ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com