The problem: every new iOS adds a lot of new useful classes. For example, UIRefreshControl. I want to add support for this class in iOS5 build.
Not cool solution: In all classes that must use UIRefreshControl, I can check for current iOS version and use inline replacement for that classes, for example:
pseudocode
...
- (void)viewDidLoad
{
...
if([[UIDevice currentDevice].systemVersion floatValue] < 6.0)
{
self.refreshControl = [[MyCustonRefreshControl_for_iOS5 alloc] init];
}
else
{
self.refreshControl = [[UIRefreshControl alloc] init];
}
...
}
This solution is't cool, because I must add same code in all classes where I want to use latest iOS features.
Possible cool solution:
1) get or create your own 100% compatible class, for example for UIRefreshControl you can use CKRefreshControl (https://github.com/instructure/CKRefreshControl);
2) use Objective-C runtime to define replacement class as main class when App starts.
pseudocode
...
// ios 5 compatibility
#include <objc/runtime.h>
#import "CKRefreshControl.h"
...
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
...
// pre-ios 6 compatibility
if([[UIDevice currentDevice].systemVersion floatValue] < 6.0)
{
// register refresh control
Class clazz = objc_allocateClassPair([CKRefreshControl class], "UIRefreshControl", 0);
objc_registerClassPair(clazz);
}
...
}
I think that this way is really cool, but this code won't work.
You may want to make one consistent interface with different ways of doing the job. You need a strategy design pattern to solve your problem. Then you need to check for version only once - at initialisation of object which is doing iOS version specific job.
If all method calls are identical (and no class/"static" methods to speak of), simply use a "factory" method to create the objects and then use them "normally".
Otherwise, I'd probably use a "wrapper" class that reroutes calls to either the builtin support or your "replacement", based on one of the tests Filip's post.
The second soultion should work fine
There's can be some issues when ARC is enabled, so, you should move allocate_pair code to some class, that is compiled with -fno-objc-arc flag
For more information, look here (in comments):
http://www.mikeash.com/pyblog/friday-qa-2010-11-6-creating-classes-at-runtime-in-objective-c.html
#abuharsky, [CKRefreshControl]https://github.com/instructure/CKRefreshControl has been updated and now does exactly what you are asking for. All you need to do is:
self.refreshControl = [[UIRefreshControl alloc] init];
Let us know if that doesn't work for you.
Related
I have been doing some research online and have found that using the ObjectiveC package in Objective C you can get a list of all the methods on a class using class_copyMethodList(), and I see you can get the implementation (IMP) of a method using instanceMethodForSelector:. The Apple documentation here has been helpful so far but I'm stuck and not sure what I'm really looking to find.
I want a list of the methods/functions called in a given method's implementation so I can build a call tree.
Any suggestions? Thanks in advance!
This solution is kind of hard way, and will cause a line of code in every method You can also make use of sqlite and save the tracked methods..
MethodTracker.h
#interface MethodTracker : NSObject
#property (nonatomic) NSMutableArray *methodTrackArr;
+ (MethodTracker *)sharedVariables;
#end
MethodTracker.m
#implementation MethodTracker
static id _instance = nil;
+ (MethodTracker *)sharedVariables
{
if (!_instance)
_instance = [[super allocWithZone:nil] init];
return _instance;
}
// optional
- (void)addMethod:(NSString *)stringedMethod
{
// or maybe filter by: -containObject to avoid reoccurance
[self.methodTrackArr addObject:stringedMethod];
NSLog("current called methods: %#", methodTrackArr);
}
#end
and using it like:
OtherClass.m
- (void)voidDidLoad
{
[super viewDidLoad];
[[MethodTracker sharedVariables] addMethod:[NSString stringWithUTF8String:__FUNCTION__]];
// or directly
[[MethodTracker sharedVariables].methodTrackArr addObject:[NSString stringWithUTF8String:__FUNCTION__]];
}
- (void)someOtherMethod
{
// and you need to add this in every method you have (-_-)..
[[MethodTracker sharedVariables] addMethod:[NSString stringWithUTF8String:__FUNCTION__]];
}
i suggest you import that MethodTracker.h inside [ProjectName]-Prefix.pch file.
Sorry, for the double answer, i deleted the other one and i have no idea how did that happen..
Hope this have helped you or at least gave you an idea.. Happy coding,
Cheers!
I think in the runtime track method is possible, but function not.
I have been build a tool DaiMethodTracing for trace all methods activity in single class for some of my need. This is based on objective-c method swizzling. So, there is an idea to do this
List all Classes in your application.
swizze all the methods in each class.
filter the method you want to trace.
finally, you may got the method call path.
So with each new OS a bunch of methods are declared deprecated. The strange thing for me is that if I want to still support iOS5 AND iOS6 I have to use BOTH the deprecated and the replacement method, like with UILabel's minimumScaleFactor over minimumFontSize.
If I replace myLabel.minimumFontSize to myLabel.minimumScaleFactor than my app will come crashing down in iOS5.
So I use an if with -respondsToSelector: to find out whether the OS is 5 or 6 and use minimumScaleFactor or minimumFontSize accordingly.
The problem is that I might have to write a bunch of ifs and respondsToSelectors in my code and that feels dumb.
Is there a better way to deal with deprecations?
I create function which i can use in any ios:
void AbsSdk30_upg60_UILabel_setMinimumScaleFactor(UILabel * label, CGFloat minimumScaleFactor) {
if ([label respondsToSelector: #selector(setMinimumScaleFactor:)]) {
[label setMinimumScaleFactor: minimumScaleFactor];
}
else {
const CGFloat curFontSize = label.font.pointSize;
const CGFloat fontSize = (0.0 == curFontSize) ? [UIFont labelFontSize] : curFontSize;
[label setMinimumFontSize: fontSize * minimumScaleFactor];
}
}
Language independend solution: get the OS at the start of your app and set a global variable. Then, when neede query the variable for the OS version. You could do it in a case/switch statement to allow for easy extensability if changes in future versions occur.
Pseudo code:
switch iOSversion
case < 6
dothis
break
case <7
dothat
break
case >7
OS not supported ;)
Technically it is the same thing as with the IFs, but your source would be shorter and more structured plus you don't have to query the OS version everytime, but once at the start of your app.
For that you should put the deployment target minimum. So that if you run your application.At that time it will not give you deprecated errors.And also you don't need to write the if s and respondsToSelectors in your code. you can put your deployment target to ios 5.0 or 5.1
I think it will work for you.
And if you want your deployment target 6.0 then there will be a another method which can replace that deprecated method.
I treat 'deprecated' as a warning that a method may go away at some point in the future, not that it has to be replaced now. Rather than complicating the code for current builds I leave myself comments about what to change when I drop support for certain older versions.
Except for things that stop working in a new release, I don't #ifdef by versions.
Add a category to UILabel like this in a .h file or in .h and .m files where the .h file will be imported by the code that uses it:
#interface UILabel (UILabelCategory)
+ (CGFloat)minimumLabelFontSize;
- (void)adjustsFontSizeToFitWidthWithMinimumFontSize:(CGFloat)fontSize;
#end
#implementation UILabel (UILabelCategory)
+ (CGFloat)minimumLabelFontSize // class method that returns a default minimum font size
{
return 11;
}
- (void)adjustsFontSizeToFitWidthWithMinimumFontSize:(CGFloat)fontSize
{
if ([self respondsToSelector: #selector(setMinimumScaleFactor:)])
{
CGFloat currentFontSize = self.font.pointSize == 0 ? [UIFont labelFontSize] : self.font.pointSize;
[self setMinimumScaleFactor:fontSize / currentFontSize];
}
else
{
[self setMinimumFontSize:fontSize]; // deprecated, only use on iOS's that don't support setMinimumScaleFactor
}
[self setAdjustsFontSizeToFitWidth:YES];
}
#end
And then call the UILabel extension like this from multiple places in your code:
(assuming that you have a UILabel object called _instructions and that you import the file that implements the UILabelCategory extension)
[_instructions adjustsFontSizeToFitWidthWithMinimumFontSize:[UILabel minimumLabelFontSize]];
or like this:
[_instructions adjustsFontSizeToFitWidthWithMinimumFontSize:14];
Note: remember that on iOS 6 and prior the setMinimumFontSize only works if you also set the number of lines to 1 like this:
[_instructions setNumberOfLines:1]; // on iOS6 and earlier the AdjustsFontSizeToFitWidth property is only effective if the numberOfLines is 1
I tried out an app to test bluetooth communication. It is a simple app that just sends a message in text form from one iDevice to another. Originally, this app had about 6 warnings but I fixed all but two. They are the same but deal with different delegates. One is for the GKPeerPickerControllerDelegate and the other for the GKSessionDelegate. Say the Picker error is for the GKPeerPickerController named picker, when you type (more complete example to follow):
picker.delegate = self;
the compiler says:
Passing '*const___strong' to parameter of incompatible type 'id'.
For the GKSession named session, typing
session.delegate = self;
makes the compiler say:
Sending '*const___strong' to parameter of incompatible type 'id'.
These only pop in the button to send and peerPickerController. I know that these warnings do not impede on the app's ability to function but I would like to completely update this for Xcode 4.2. This app was originally written for Xcode back when iOS 3.0 was new. Yes, I am a bit picky when it comes to writing or practicing code, it must not contain any errors/warnings whenever possible.
These are the code blocks where the warning occur:
-(IBAction)btnConnect:(id)sender{
picker = [[GKPeerPickerController alloc] init];
picker.delegate = self; //Warning here
picker.connectionTypesMask = GKPeerPickerConnectionTypeNearby;
[connect setHidden:YES];
[disconnect setHidden:NO];
[picker show];
}
-(void)peerPickerController:(GKPeerPickerController *)PCpicker didConnectPeer:(NSString *)peerID toSession:(GKSession *)session{
self.currentSession = session;
session.delegate = self; //Warning here
[session setDataReceiveHandler:self withContext:nil];
PCpicker.delegate = nil;
[PCpicker dismiss];
}
Edit:
The header has this:
#interface BTViewController : UIViewController{
GKSession *currentSession;
IBOutlet UITextField *txtMessage;
IBOutlet UIButton *connect;
IBOutlet UIButton *disconnect;
GKPeerPickerController *picker;
}
I believe whatever class self is may not be adopting the GKPeerPickerControllerDelegate and GKSessionDelegate formal protocols. Can you post your interface header?
EDIT
Casting to id will clear the warnings, but you really didn't "fix" anything...looking at the class header, it is not adopting the protocols that the delegates are expecting.
Modify your interface to adopt those protocols:
#interface BTViewController : UIViewController <GKPeerPickerControllerDelegate, GKSessionDelegate> {
What about session.delegate = (id)self. Maybe you just need to cast self as ID instead of const____strong.
EDIT: At the bequest of the OP, an explanation is in order. Type id is necessary for the protocol, because the protocol itself is literally typecast to id itself (id<GKSessionDelegate> etc.). My theory (because I am not using ARC in any of my projects) Is that the compiler gets very exacting so it can guarantee that your class is safe for release. You probably initialized your class in a non-id way... Of course I have no idea how, if anyone knows; I'd be happy to let them edit this answer.
EDIT 2: as Teddy said, adopting the protocols in your header file also silences this warning. I apologize for thinking it was implied that you had adopted the protocols.
What is the recommended method of styling an iOS app? For example, if there are multiple labels or text views how can updating font style/color at one place update the style/color at all other places?
I know sub classing could be one way... is there any other way?
You could import a standard header file into all your controllers with several constants set for styling... example:
Styles.h
#define kFontSize 14
#define kFontFamily #"Helevetica"
Controller
#import "Styles.h" // at the top
myLabel.font = [UIFont fontWithName:kFontFamily size:kFontSize];
I personally think Interface Builder is the best way to style, however this answers your question directly.
Update: I would recommend starting by understanding UIAppearance APIs, and seeing how well they suit your needs. UIAppearance is a convenient way to provide custom default stylization of specific controls' attributes at multiple levels (e.g. globally or contextually).
My original answer, which predated UIAppearance's availability:
since we're working with an object based language...
for the implementation, it depends on how you want it to behave/execute. when the implementation becomes nontrivial, i will often create a protocol. you could use class methods or instance methods and significantly optimize these types for your usage because you create fewer intermediate colors, fonts, images, etc.
a basic interface could take the form:
#protocol MONLabelThemeProtocol
- (UIFont *)labelFont;
- (UIColor *)labelTextColor;
- (UITextAlignment)labelTextAlignment;
// ...
#end
#protocol MONTableViewCellThemeProtocol
- (UIFont *)tableViewCellFont;
- (UIColor *)tableViewCellTextColor;
- (UIImage *)tableViewCellImage;
- (NSInteger)tableViewCellIndentationLevel;
- (CGFloat)tableViewCellIndentationWidth;
// ...
#end
then a simple amalgamate theme could be declared like this:
#interface MONAmalgamateThemeBase : NSObject
< MONLabelThemeProtocol, MONTableViewCellThemeProtocol >
{
#protected
/* labels */
UIFont * labelFont;
UIColor * labelTextColor;
UITextAlignment labelTextAlignment;
// ...
/* table view cells */
UIFont * tableViewCellFont;
UIColor * tableViewCellTextColor;
UIImage * tableViewCellImage;
NSInteger tableViewCellIndentationLevel;
CGWidth tableViewCellIndentationWidth;
// ...
}
#end
in this example, the amalgamate defines the getters and dealloc and expects the subclasses to initialize the instance variables. you could also support lazy initialization if initialization times are high (e.g. uses many images).
then a specialization could take the form:
#interface MONDarkTheme : MONAmalgamateThemeBase
#end
#implementation MONDarkTheme
- (id)init
{
self = [super init];
if (nil != self) {
labelFont = [[UIFont boldSystemFontOfSize:15] retain];
labelTextColor = [[UIColor redColor] retain];
// and so on...
}
return self;
}
// ...
#end
/* declare another theme and set it up appropriately */
#interface MONLightTheme : MONAmalgamateThemeBase
#end
then just reuse the theme instances (e.g. MONDarkTheme) throughout the app to stylize the views. if you have a lot of themes or they are not trivial to construct, then you may want to create a collection for themes (theme manager). the amalgamate could also take a parameter, such as init with theme if your needs are simple. you can even configure objects to register for changes to themes, if you need support for dynamic changes.
finally, you can create a simple theme applier to make life easier - like so:
#interface UILabel (MONThemeAdditions)
- (void)mon_applyMONLabelTheme:(id<MONLabelTheme>)theme;
#end
#implementation UILabel (MONThemeAdditions)
- (void)mon_applyMONLabelTheme:(id<MONLabelTheme>)theme
{
assert(theme);
if (nil == theme) return;
self.font = [theme labelFont];
self.textColor = [theme labelTextColor];
self.textAlignment = [theme labelTextAlignment];
}
#end
Frankly, the best way to go about this is to use Interface Builder. While it might seem nice to change a single constant somewhere in the code and have the entire app change styles, it never quite works out that way. Here are my reasonings:
1) Developers don't write interface code as well as interface builder does.
Interface builder is a tool that has been refined, tested, and intreated over years. It offers fonts, text alignment, shadow, etc. It is backwards compatible for as far back as you'd ever want. It provides a very simple way for any number of developers and designers to jump in and work on something very straightforward.
2) There are always edge cases that you'll have to account for. Sure, a simple constant will do what you want most the time, but you'll eventually have to hack something in here and sneak something in there. The "simple" interface code you wrote to start off will grow and grow and grow. Other developers will have to maintain that code. You will have to maintain that code. You will have to file and fix bugs, tweak this, except that, etc. It will inevitably become a steaming pile of mess.
3) The more code you write, the more bugs you write. Interface builder is for building the 'look' of most iOS apps. Use it. Don't get too clever.
NOTE:
I understand that Interface builder cannot do everything for all apps. There are cases that coding an interface is the only solution. This answer is simply a general "best practice" I use in the bulk of my apps.
Similar to Alex's idea, you could create a static class called ThemeManager:
typedef enum
{
defaultStyle,
redStyle,
} ThemeStyles;
#interface Level : NSObject
{
ThemeStyles currentTheme;
}
All classes which can be themed will import ThemeManager. Then, you can create methods like:
+ (UIColor*) fontColor;
Which other classes would call when they want a color for their font. Then, if you want to change themes, you could implement fontColor as:
+ (UIColor*) fontColor
{
switch (currentTheme)
{
case defaultStyle:
return [UIColor blackColor];
case redStyle:
return [UIColor redColor];
}
}
When you want to change the theme, you could have ThemeManager implement a method like:
+ (void) changeTheme:(ThemeStyles)newTheme
{
currentTheme = newTheme;
}
You can use a third-party abstraction of UIAppearance:
NUI: https://github.com/tombenner/nui
Pixate: http://www.pixate.com
Using a Storyboard has a lot of benefits, but many style options aren't available, not the least of which is custom fonts. If you want a deeply-customized UI, you will need some style code to make it happen.
I use plists. Just as I localize strings, I use the same procedure to change themes. I coded a singleton that loads a current theme plist and a fallback plist. Then I replace the names of resources with keys and macro functions that pull the real resource name from the singleton.
Cons: you have to set the resource for each element, not just set it in the NIB.
Pros: once you are done, most of the next theme involves photoshop and textmate, not IB or code.
You may need to look at this library. It supports multiple themes/skins on the fly. Supports images and colors currently. Font support will be added in future.
https://github.com/charithnidarsha/MultiThemeManager
I decided to start learning some Obj-C. And I thought that Wikibooks wikidraw application would be a good place to start (after some very basic "Hello World" programs). I've followed the chapters and now I'm at the end of "WikiDraws view class". So now I'm supposed to be able to compile and run. Of course it dosen't work. I got a lot of errors at first but i have fixed most of them, only 6 remaining. This is one of them:
- (void) mouseDragged:(NSPoint) pt
{
NSPoint np;
np.x = pt.x - _anchor.x;
np.y = pt.y - _anchor.y;
if ( _dragState == 0) {
// dragging of object
[self offsetLocationByX:np.x byY:np.y];
}
else if ( _dragState >= 1 && _dragState < 9 )
{
// dragging a handle
NSRect nb = [self newBoundsFromBounds:[self bounds] forHandle:_dragState withDelta:np];
[self setBounds:nb];
}
}
- (NSRect) newBoundsFromBounds:(NSRect) old forHandle:(int) whichOne withDelta:(NSPoint) p
{
// figure out the desired bounds from the old one, the handle being dragged and the new point.
NSRect nb = old;
switch( whichOne )
{ ..........
So at
NSRect nb = [self newBoundsFromBounds:...
I get an error message, "Invailid initializer" and "WKDShape may not respond to '-newBoundsFromBounds:forHandle:withDelta:"- . What should I do? I'm new to coding but eager to learn.
/Carl-Philip
Assuming you've pasted that code in the order written in your source code and newBoundsFromBounds:forHandle:withDelta: isn't declared (as distinct from being defined) at some earlier point, I think the problem is just that at nb = [self newBoundsFromBounds:... the compiler doesn't yet know what the return type will be. An NSRect is a C-style struct rather than an Objective-C class, so the compiler really does need to know.
As a solution, either put the definition of newBoundsFromBounds:... before mouseDragged:, add it to the #interface in your header file if you want it to be exposed to everyone or declare it internally to the implementation file as a category method. To do the final one, add the following to the top of your .m, assuming your class is called WikiDrawsView:
#interface WikiDrawsView (private)
- (NSRect)newBoundsFromBounds:(NSRect) old
forHandle:(int) whichOne
withDelta:(NSPoint) p;
#end
The 'private' is just a name you get to pick, it has no special meaning. Something like 'private' is often used to signify that you're using a category in a similar way that you might use private class member functions in C++ or a language like that.
The quick way to describe categories is that they patch additional methods onto existing classes at runtime, and they use the #interface [classname] ([category name]) syntax, with no member variable section. I'm sure your tutorial will get to them, Apple's documentation on them is here. This is a common use of categories but not the primary use.
To address the "WKDShape may not respond" warning, make sure you declare -newBoundsFromBounds:forHandle:withDelta: before -mouseDragged:. You can add it to the public interface in "WKDShape.h", or in an anonymous category in "WKDShape.m".