How to use CAGradientLayer? - iphone

I'm getting up to speed with the new APIs introduced in OS 3.0, especially the cool new improvements to Core Animation (mostly on CALayer etc...). Now I'm trying to figure out how to use CAGradientLayer. It looks simple at first, but the NSArray it requires for the colors property must contain CGColorRef (according to the header file). I've tried casting to (id), but then the NSArray seems to contain NSCFType objects, which doesn't sound good.
Anybody figured how to use it or could point to some good code samples?
Thanks

Even though the NSCFType objects in the array "don't sound good", you are supposed to use CGColorRefs directly in the array. The same principle applies here as for the animation question I asked a while back. The examples I've seen for using this class all employ arrays of CGColorRefs.

Related

Objective-C Data Structures (Building my own DAWG)

After not programming for a long, long time (20+ years) I'm trying to get back into it. My first real attempt is a Scrabble/Words With Friends solver/cheater (pick your definition). I've built a pretty good engine, but it's solves the problems through brute force instead of efficiency or elegance. After much research, it's pretty clear that the best answer to this problem is a DAWG or CDWAG. I've found a few C implementations our there and have been able to leverage them (search times have gone from 1.5s to .005s for the same data sets).
However, I'm trying to figure out how to do this in pure Objective-C. At that, I'm also trying to make it ARC compliant. And efficient enough for an iPhone. I've looked quite a bit and found several data structure libraries (i.e. CHDataStructures ) out there, but they are mostly C/Objective-C hybrids or they are not ARC compliant. They rely very heavily on structs and embed objects inside of the structs. ARC doesn't really care for that.
So - my question is (sorry and I understand if this was tl;dr and if it seems totally a newb question - just can't get my head around this object stuff yet) how do you program classical data structures (trees, etc) from scratch in Objective-C? I don't want to rely on a NS[Mutable]{Array,Set,etc}. Does anyone have a simple/basic implementation of a tree or anything like that that I can crib from while I go create my DAWG?
Why shoot yourself in the foot before you even started walking?
You say you're
trying to figure out how do this in pure Objective-C
yet you
don't want to rely on a NS[Mutable]{Array,Set,etc}
Also, do you want to use ARC, or do you not want to use ARC? If you stick with Objective-C then go with ARC, if you don't want to use the Foundation collections, then you're probably better off without ARC.
My suggestion: do use NS[Mutable]{Array,Set,etc} and get your basic algorithm working with ARC. That should be your first and only goal, everything else is premature optimization. Especially if your goal is to "get back into programming" rather than writing the fastest possible Scrabble analyzer & solver. If you later find out you need to optimize, you have some working code that you can analyze for bottlenecks, and if need be, you can then still replace the Foundation collections.
As for the other libraries not being ARC compatible: you can pretty easily make them compatible if you follow some rules set by ARC. Whether that's worthwhile depends a lot on the size of the 3rd party codebase.
In particular, casting from void* to id and vice versa requires a bridged cast, so you would write:
void* pointer = (__bridge void*)myObjCObject;
Similarly, if you flag all pointers in C structs as __unsafe_unretained you should be able to use the C code as is. Even better yet: if the C code can be built as a static library, you can build it with ARC turned off and only need to fix some header files.

NSOrderedSet for iPhone?

For some odd reason NSOrderedSet does not appear to be implemented in iOS. Is there another object that gives similar functionality -- basically the ability to insert/remove objects randomly and access the first/last in sort order?
It seems to me that something like this would be needed in order to implement basic FIFO queues and the like.
Edit: I ended up doing an RYO solution.
One option is this open source data structures library:
http://dysart.cs.byu.edu/CHDataStructures/index.html
In that library is a CHOrderedSet
http://dysart.cs.byu.edu/CHDataStructures/interface_c_h_ordered_set.html
It's only dependency is NSMutableSet so it should work across all your iOS versions.
EDIT:
As Bourne pointed out above, it's also in iOS5 (reference):
The new NSOrderedSet collection class offers the semantics of sets,
whereby each element occurs at most once in the collection, but where
elements are in a specific order.
CHOrderedSet is a good option if you don't have a hard dependency on iOS5.
NSOrderedSet and NSMutableOrderedSet are not available in iOS 5. Here's the reference for anyone curious:
http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSMutableOrderedSet_Class/Reference/Reference.html#//apple_ref/occ/cl/NSMutableOrderedSet

Replace these OpenGL functions with OpenGL ES?

I search for a possibility to migrate my PC OpenGL application and an iPhone App into one XCode project (for convenience). So if I make chances to these source files I want to apply this for both plattforms and want to be able to compile for both plattforms from one project. How could I accomplish this?
Is there a way to do so in XCode 4 or 3.25? Any help would be highly appreciated
edit: Okay, I went so far - All in all, it seems to work with XCode 4.
My only problems are these openGL/Glut functions, that aren't working on iPhone:
glPushAttrib( GL_DEPTH_BUFFER_BIT | GL_LIGHTING_BIT );
glPopAttrib();
glutGet(GLUT_ELAPSED_TIME);
glutSwapBuffers();
Any ideas how to fix these issues?
PushAttrib/PopAttrib you'll need to replace yourself with code which manually tracks those states, or you could rewrite your code in such a way that anything which relies on those states, sets them itself.
glutGet(GLUT_ELAPSED_TIME) could be replaced by mach_absolute_time (not particularly easy, but the right thing to use) or [NSDate timeIntervalSinceReferenceDate] (easy, but potentially problematic since it's not guaranteed to be monotonically increasing, or to increase at 1.0 per second)
glutSwapBuffers will be replaced by -presentRenderbuffer: on your EAGLContext (but it sounds like you're already doing this; if you weren't, you wouldn't be able to see anything).
You could use dgles to wrap your desktop OpenGL implementation and provide a OpenGL ES 1.x interface.
I found this documentation online in regards to the OpenGL ES 1.0 specification
There are several reasons why one type or another of internal state needs to be queried by an ap- plication.The application may need to dynamically discover implementation limits (pixel component sizes, texture dimensions, etc.), or the application might be part of a layered library and it may need to save and restore any state that it disturbs as part of its rendering.PushAttrib andPopAttrib can be used to perform this but they are expensive to implement and use and therefore not supported.Gen- erally speaking state queries are discouraged as they are often detrimental to performance.Rather than trying to partition different types of dynamic state that can be queried, tops of matrix stacks for example, no dynamic state queries are supported and applications must shadow state changes rather than querying the pipeline.This makes things difficult for layered libraries, but there hasn’t been enough justification to retain dynamic state queries or attribute pushing and popping.
That and this other link here seems to indicate that you'll need to keep track of those bits yourself. No help for you there.
glut just calls the system code, yeah? (wglSwapBuffers, glxSwapBuffers)
Try this here eglSwapBuffers and maybe this book out
Sorry I don't have a more concrete answer for you.
very annoyed by this lack seemingly simple functionality of pushing attribs, but you can use glGetto get the state of something before you set the param , like this which worked for me:
Boolean tmpB;
int tmpSrc,tmpDst;
glGetBooleanv(GL_BLEND,&tmpB);
glGetIntegerv(GL_BLEND_SRC_ALPHA,&tmpSrc);
glGetIntegerv(GL_BLEND_DST_ALPHA,&tmpDst);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//draw rectangle
CGSize winSize=[[CCDirector sharedDirector] winSize];
CGPoint vertices[] = { ccp(0,0), ccp(winSize.width,0), ccp(winSize.width,20), ccp(0,20) };
glColor4ub(255, 0, 255, 55);
ccFillPoly( vertices, 4, YES);
if(!tmpB)
glDisable(GL_BLEND);
glBlendFunc(tmpSrc, tmpDst);

How do you minimize repeating yourself when working with UITableViewControllers

When I work with UITableViewControllers - especially when using NSFetchedResultsController - I find myself repeating a lot of base functionality on every controller. Which I hate. I'd much rather love to write these methods once and keep it all neat and tidy.
So I was wondering: What do you guys do to not repeat yourself writing UIViewControllers. How do you DRY up your code. Inheritance, protocols, whatever.
Thanks! Looking forward to your answers.
(Since this question doesn't have a definitive answer, I will accept the one I find the best.
Is that the way to do it?)
You can write your own controllers with the basic functionality and then subclass and reuse them. Check the CoreDataTableViewController class that was built for the Stanford iPhone Application Development course -> http://www.stanford.edu/class/cs193p/cgi-bin/drupal/node/167
One technique is to subclass your own subclass. This, modularizes and isolates the differences nicely, however it generates a lot of classes and files, which some find harder to read.
Another technique, which you can use when you want to create a bunch of almost identical controllers with just slight differences, is to give one class a "type" parameter or instance variable. Set the controller's type when you init a controller, and use the controller's type in "if" or switch statements (etc.) to select between slight differences in controller behaviors at run-time. This can help keep all the differences more compactly located in source code.
I made this new Core Data wrapper for iOS in Swift - https://github.com/tadija/AERecord
It has Swift version of CoreDataTableViewController, and CoreDataCollectionViewController also.
Beside that you can use it to setup Core Data stack like this:
AERecord.setupCoreDataStack()
Access context for current thread like this:
AERecord.defaultContext
Save context like this:
AERecord.saveContext()
Create fetch requests like this:
NSManagedObject.create()
NSManagedObject.firstOrCreateWithAttribute("city", value: "Belgrade")
NSManagedObject.deleteAll()
let predicate = ...
NSManagedObject.firstWithPredicate(predicate)
NSManagedObject.allWithAttribute("year", value: 1984)
And much more... I hope it will be useful for someone.

What's better: Writing functions, or writing methods? What costs more performance?

Currently I am making some decisions for my first objective-c API. Nothing big, just a little help for myself to get things done faster in the future.
After reading a few hours about different patterns like making categories, singletons, and so on, I came accross something that I like because it seems easy to maintain for me. I'm making a set of useful functions, that can be useful everywhere.
So what I did is:
1) I created two new files (.h, .m), and gave the "class" a name: SLUtilsMath, SLUtilsGraphics, SLUtilsSound, and so on. I think of that as kind of "namespace", so all those things will always be called SLUtils******. I added all of them into a Group SL, which contains a subgroup SLUtils.
2) Then I just put my functions signatures in the .h file, and the implementations of the functions in the .m file. And guess what: It works!! I'm happy with it, and it's easy to use. The only nasty thing about it is, that I have to include the appropriate header every time I need it. But that's okay, since that's normal. I could include it in the header prefix pch file, though.
But then, I went to toilet and a ghost came out there, saying: "Hey! Isn't it better to make real methods, instead of functions? Shouldn't you make class methods, so that you have to call a method rather than a function? Isn't that much cooler and doesn't it have a better performance?" Well, for readability I prefer the functions. On the other hand they don't have this kind of "named parameters" like methods, a.f.a.i.k..
So what would you prefer in that case?
Of course I dont want to allocate an object before using a useful method or function. That would be harrying.
Maybe the toilet ghost was right. There IS a cooler way. Well, for me, personally, this is great:
MYNAMESPACECoolMath.h
#import <Foundation/Foundation.h>
#interface MYNAMESPACECoolMath : NSObject {
}
+ (float)randomizeValue:(float)value byPercent:(float)percent;
+ (float)calculateHorizontalGravity:(CGPoint)p1 andPoint:(CGPoint)p2;
// and some more
#end
Then in code, I would just import that MYNAMESPACECoolMath.h and just call:
CGFloat myValue = [MYNAMESPACECoolMath randomizeValue:10.0f byPercent:5.0f];
with no nasty instantiation, initialization, allocation, what ever. For me that pattern looks like a static method in java, which is pretty nice and easy to use.
The advantage over a function, is, as far as I noticed, the better readability in code. When looking at a CGRectMake(10.0f, 42.5f, 44.2f, 99.11f) you'll may have to look up what those parameters stand for, if you're not so familiar with it. But when you have a method call with "named" parameters, then you see immediately what the parameter is.
I think I missed the point what makes a big difference to a singleton class when it comes to simple useful methods / functions that can be needed everywhere. Making special kind of random values don't belong to anything, it's global. Like grass. Like trees. Like air. Everyone needs it.
Performance-wise, a static method in a static class compile to almost the same thing as a function.
Any real performance hits you'd incur would be in object instantiation, which you said you'd want to avoid, so that should not be an issue.
As far as preference or readability, there is a trend to use static methods more than necessary because people are viewing Obj-C is an "OO-only" language, like Java or C#. In that paradigm, (almost) everything must belong to a class, so class methods are the norm. In fact, they may even call them functions. The two terms are interchangeable there. However, this is purely convention. Convention may even be too strong of a word. There is absolutely nothing wrong with using functions in their place and it is probably more appropriate if there are no class members (even static ones) that are needed to assist in the processing of those methods/functions.
The problem with your approach is the "util" nature of it. Almost anything with the word "util" it in suggests that you have created a dumping ground for things you don't know where to fit into your object model. That probably means that your object model is not in alignment with your problem space.
Rather than working out how to package up utility functions, you should be thinking about what model objects these functions should be acting upon and then put them on those classes (creating the classes if needed).
To Josh's point, while there is nothing wrong with functions in ObjC, it is a very strongly object-oriented language, based directly on the grand-daddy of object-oriented languages, Smalltalk. You should not abandon the OOP patterns lightly; they are the heart of Cocoa.
I create private helper functions all the time, and I create public convenience functions for some objects (NSLocalizedString() is a good example of this). But if you're creating public utility functions that aren't front-ends to methods, you should be rethinking your patterns. And the first warning sign is the desire to put the word "util" in a file name.
EDIT
Based on the particular methods you added to your question, what you should be looking at are Categories. For instance, +randomizeValue:byPercent: is a perfectly good NSNumber category:
// NSNumber+SLExtensions.h
- (double)randomizeByPercent:(CGFloat)percent;
+ (double)randomDoubleNear:(CGFloat)percent byPercent:(double)number;
+ (NSNumber *)randomNumberNear:(CGFloat)percent byPercent:(double)number;
// Some other file that wants to use this
#import "NSNumber+SLExtensions.h"
randomDouble = [aNumber randomizeByPercent:5.0];
randomDouble = [NSNumber randomDoubleNear:5.0 byPercent:7.0];
If you get a lot of these, then you may want to split them up into categories like NSNumber+Random. Doing it with Categories makes it transparently part of the existing object model, though, rather than creating classes whose only purpose is to work on other objects.
You can use a singleton instance instead if you want to avoid instantiating a bunch of utility objects.
There's nothing wrong with using plain C functions, though. Just know that you won't be able to pass them around using #selector for things like performSelectorOnMainThread.
When it comes to performance of methods vs. functions, Mike Ash has some great numbers in his post "Performance Comparisons of Common Operations". Objective-C message send operations are extremely fast, so much so that you'd have to have a really tight computational loop to even see the difference. I think that using functions vs. methods in your approach will come down to the stylistic design issues that others have described.
Optimise the system, not the function calls.
Implement what is easiest to understand and then when the whole system works, profile it and speed up what's slow. I doubt very much that the objective-c runtime overhead of a static class is going to matter one bit to your whole app.