iOS笔记


svn status '~'

2012-11-21 17:35 by -king, 4 阅读, 0 评论, 收藏编辑

svn status 出现'~'时 提交会显示错误 xx/xx.svn' containing working copy admin area is missing

’~’Item is versioned as one kind of object (file, directory, link), but has been replaced by different kind of object.

解决办法:先把'~'状态的文件夹改为其他名字 删除文件夹并提交 在把名字改回来 添加并提交 

1. mv Test Test1 2. svn remove Test 3. svn commit -m "Removed Test" 4. mv Test1 Test 5. svn add Test 6. svn commit -m "Added Test"


GMGridView cell button

2012-11-16 21:26 by -king, 6 阅读, 0 评论, 收藏编辑

在GMGridView的cell里面添加button的时候,不能响应touch up inside事件。

解决方法:https://github.com/gmoledina/GMGridView/issues/68

在gmgridview.m文件中作修改,添加以下方法可解决问题。

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ( gestureRecognizer == _tapGesture || gestureRecognizer == _sortingLongPressGesture ) {
        if ( [touch.view isDescendantOfView:self] ) {
            // Test if the touched view is a subview of a control
            for ( UIView *view = touch.view ; view != self ; view = view.superview )
                if ( [view isKindOfClass:[UIControl class]] )
                    return NO;
        }
    }

    return YES;
}

[OBJC]NSNumber *number = [NSNumber numberWithInt:yourIntValue];
[[NSUserDefaults standardUserDefaults] setObject:number forKey :mad: "YourKey"];[/OBJC]

NSUserDefaults can only store objects. So convert your integer to a NSNumber object and set that. Recall it with objectForKey.
 

NSInteger和Int的转换

  4326人阅读  评论(0)  收藏  举报

NSString *a = @"234";

int abc = [a intValue];

…..

doubleValue;

floatValue;

boolValue;

integerValue;

-----------------------------------------------------

 

NSInteger转换为int:

NSInteger myInteger = 32;

int myInt = myInteger;

NSLog(@"myInt = %d", myInt);

 

附录:

#if __LP64__ || TARGET_OS_EMBEDDED || TARGET_OS_IPHONE || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64 

typedef long NSInteger;

#else

typedef int NSInteger;

#endif

2012

May

07

iOS开发之int,NSInteger,NSUInteger,NSNumber的使用
文章分类: iOS开发

1、当需要使用int类型的变量的时候,可以像写C的程序一样,用int,也可以用NSInteger,但更推荐使用NSInteger,因为这样就不用考虑设备是32位的还是64位的。

2、NSUInteger是无符号的,即没有负数,NSInteger是有符号的。

3、有人说既然都有了NSInteger等这些基础类型了为什么还要有NSNumber?它们的功能当然是不同的。

NSInteger是基础类型,但是NSNumber是一个类。如果想要存储一个数值,直接用NSInteger是不行的,比如在一个Array里面这样用:

NSArray *array= [[NSArray alloc]init];
[array addObject:3];//会编译错误

这样是会引发编译错误的,因为NSArray里面放的需要是一个类,但‘3’不是。这个时候需要用到NSNumber:

NSArray *array= [[NSArray alloc]init];
[array addObject:[NSNumber numberWithInt:3]];

Cocoa提供了NSNumber类来包装(即以对象形式实现)基本数据类型。

例如以下创建方法:

+ (NSNumber*)numberWithChar: (char)value;
+ (NSNumber*)numberWithInt: (int)value;
+ (NSNumber*)numberWithFloat: (float)value;
+ (NSNumber*)numberWithBool: (BOOL) value;

将基本类型数据封装到NSNumber中后,就可以通过下面的实例方法重新获取它:

- (char)charValue;
- (int)intValue;
- (float)floatValue;
- (BOOL)boolValue;
- (NSString*)stringValue;


单子模式:

Global Variables in iPhone Objective-C

If you studied any programming in school you were probably told to never use global variables because ultimately it can cause you end up with a messy slob of code that is difficult to maintain, and this holds true in iPhone Objective-C.

While that is correct, the truth of the matter is there are many situations when you want to have a global variable, as often there are variables that don’t really belong to any objects, and you want to change them from many locations within your application.  You could of course place variables in your AppDelegate and access them through there, but this is not a good solution and can turn things into a great big mess which is the reason why many college professors forbid the use of global variables in all languages (not simply because they may have never actually coded anything).  The solution to this is to create a class using the Singleton design pattern.  For example:

@interface VariableStore : NSObject

{

    // Place any "global" variables here

}

// message from which our instance is obtained

+ (VariableStore *)sharedInstance;

@end


@implementation VariableStore

+ (VariableStore *)sharedInstance

{

    // the instance of this class is stored here

    static VariableStore *myInstance = nil;

 

    // check to see if an instance already exists

    if (nil == myInstance) {

        myInstance  = [[[self class] alloc] init];

        // initialize variables here

    }

    // return the instance of this class

    return myInstance;

}

@end

Whenever you need to access a variable assuming you have a getter defined as the variable name simply use:

[[VariableStore sharedInstance] variableName]

If the variable is a primitive, and a global constant then there is really no need to use a singleton as above you can use a preprocessor #define statement. For example:

#define VARIABLE value

Now when you need to share a variable between many objects this should make for much simpler, and cleaner code.

If you’re transitioning to Objective-C from C/C++/Java you might want to check out myObjective-C Cheat Sheet.



iPhone : How to save a view as image ??? (ex.save what you draw )


9
down vote accepted
UIGraphicsBeginImageContext(view.bounds.size);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

This gives the image which you can store using –

NSData *imageData = UIImageJPEGRepresentation(image, 1.0):
[imageData writeToFile:path atomically:YES];

where path is location you want to save to.

share | improve this answer
 
sorry , can you tell more detail about this code ... I have no idea to use it ... –  WebberLai  May 21 '11 at 4:37
1  
The idea is to generate a UIImage object for the view so that we can save it as an image. For that we use a bit of Core Graphics. We take the view's layer (each view has a layer which represents the visual aspect of the view) and draw it into an image context (Imagine context as a drawing board). Once the drawing is finished, we generate the UIImage object of the context. This we convert to data in jpeg representation using a framework function UIImageJPEGRepresentation(image,1.0). Note the 1.0 is the quality of the image you desire with 1.0 being the best –  Deepak Danduprolu  May 21 '11 at 6:34
 
Once we have an NSData object we use its method writeToFile:atomically to save the image at the desired file path. Hope this is what you were looking for. –  Deepak Danduprolu  May 21 '11 at 6:35

http://www.cnblogs.com/wangkewei/archive/2012/10/10/2718641.html

GET and POST

No milestone
No one is assigned

GET is working in this code...

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:SERVER]];
NSMutableURLRequest *request;
request = [httpClient requestWithMethod:@"GET" 
                               path:PATH 
                             parameters:parameters];

POST is not...

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:SERVER]];
NSMutableURLRequest *request;
request = [httpClient requestWithMethod:@"POST" 
                               path:PATH 
                             parameters:parameters];

Not sure if it is me, but when I try and POST, the parameters are not working. I switch to GET and it forms the QueryString OK and sends, with exactly the same parameters...

https://github.com/AFNetworking/AFNetworking/issues/94

AFNetworking Post Request

http://stackoverflow.com/questions/7623275/afnetworking-post-request


iOS中正则表达式的使用--NSPredicate

http://www.2cto.com/kf/201208/150608.html

http://stackoverflow.com/questions/10758235/proper-nspredicate-for-find-or-create-pattern-in-core-data

Filtering Arrays With NSPredicate


Core Data - How to Do a SELECT DISTINCT

http://felipecypriano.com/2011/09/21/core-data-how-to-do-a-select-distinct/


一个去除NSArray中重复数据的方法

categoryArray = [[NSMutableArray alloc] init]; for (unsigned i = 0; i < [cateArray count]; i++){ if ([categoryArray containsObject:[cateArray objectAtIndex:i]] == NO){ [categoryArray addObject:[cateArray objectAtIndex:i]]; }


       文摘。

清华差生10年奋斗经历


http://www.chuangyejia.com/archives/14359.html/2 


Popover from tableViewCell positioning issue

http://stackoverflow.com/questions/8645388/popover-from-tableviewcell-positioning-issue

NSPredicate usage:


NSPredicate *predicate = [[NSPredicate alloc] initWithFormat:@"isChecked == YES"];

Then we'll use the -filteredArrayUsingPredicate: method on NSArray to get an NSArray of all the objects which match the predicate.

NSArray *filteredArray = [originalArray filteredArrayUsingPredicate:predicate];

//NSArray * myArray is your array 
//containing your objects that each have an isChecked property


NSPredicate *predicate = [NSPredicate predicateWithFormat:@"isChecked == YES"];
NSArray *filteredArray = [myArray filteredArrayUsingPredicate:predicate];

// filteredArray is the new array that only contains your checked items


Animate popoverContentsize when pushing navigation view controller in popover on iPad

 keeping a reference to the popoverController and usedsetPopoverContentSize:animated:

What works for me is this combination of setPopoverContentSize:animated: ANDcontentSizeForViewInPopover in that specific order, for each controller your put on the stack:

-(void)viewDidAppear:(BOOL)animated
{
    [self.popoverController setPopoverContentSize:whateverSize animated:true];
    self.contentSizeForViewInPopover = whateverSize;
    [super viewDidAppear:animated];
}

In this case, self.popoverController is a reference I keep in each controllers that is pushed on the stack, it would probably be cleaner to use a singleton variable for that.


 

定制UINavigationBar

分类: iOS   838人阅读  评论(4)  收藏  举报

在开发中经常需要定制某些界面,navigationController的navigationBar就是一个很典型的例子,比如要修改背景图、后退按钮等等。

背景图的修改很简单,但是需要了解iOS的框架,假设我给自己定制的UINavigationController增加一个接口用于修改背景图:

  1. @property (nonatomic, retain) UIImage *backgroundImage;  
那么该消息的实现如下:

  1. -(void)setBackgroundImage:(UIImage *)backgroundImage{  
  2.     if ([self.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]) {  
  3.         [self.navigationBar setBackgroundImage:backgroundImage forBarMetrics:UIBarMetricsDefault];  
  4.         return;  
  5.     }  
  6.     self.navigationBar.layer.contents = (id)backgroundImage.CGImage;  
  7. }  

iOS 5增加了大量API,可以基本满足我们的定制需求,所以如果是iOS 5,我们直接调5的API就行了,而最后一行代码是针对5以下的,也就是说这一行代码就可以修改了,写起来容易但是要知道为什么。众所周知一个视图如何显示是取决于它的drawRect方法,因为调这个方法之前iOS也不知道如何显示它,但其实drawRect方法的目的也是画图(显示内容),而且我们如果以其他的方式给出了内容(图)的话,drawRect方法就不会被调用了。

注:实际上UIView是CALayer的delegate,如果CALayer没有内容的话,会回调给UIView的displayLayer:或者drawLayer:inContext:方法,UIView在其中调用drawRect,draw完后的图会缓存起来,除非使用setNeedsDisplay或是一些必要情况,否则都是使用缓存的图。

虽然往navigationBar里面插入一个imageView也能达到这种目的,但是要麻烦得多,因为你要自己管理navigationBar的视图层级,原因在于iOS 4和iOS 5的版本不同,往navigationBar插入视图的位置是相反的,不处理的话会导致部份子视图被遮住。

-----------------------------------------猥琐的分界线-----------------------------------------

如果只想更改后退按钮的标准属性,比如title、target、action,那么就:

  1. UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] init];  
  2. backButtonItem.title = @"已改的";  
  3. backButtonItem.target = self;  
  4. backButtonItem.action = @selector(back);  
  5. self.navigationItem.backBarButtonItem = backButtonItem;  
  6. [backButtonItem release];  
只要注意一点,这个设置是 针对于子导航层级的,也就是你push到下个视图控制器的时候才会看到。

如果是想更改字体、颜色、背景之类的,就要用到UIButton了:

  1. UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];  
  2. [back setTitle:@"已改" forState:UIControlStateNormal];  
  3. [back setFrame:CGRectMake(0, 0, 100, 32)];  
  4. [back setBackgroundColor:[UIColor redColor]];  
  5. UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:back];  
  6. self.navigationItem.leftBarButtonItem = backButtonItem;  
  7. [backButtonItem release];  
完全当成一个button来用,注意和上面的不同:赋给了 leftBarButtonItem

如果你不知道何时添加这个自己的后退按钮?很简单,判断navigationBar.backItem有没有就行了,跟着系统走是不会错的,不过可能要再判断一下当前显示的viewController有没有用到leftBarButtonItem,不要覆盖掉逻辑就行了。




http://blog.csdn.net/cocoa_geforce/article/details/7357964  NSdate 时区。


http://zbar.sourceforge.net/iphone/sdkdoc/install.html  

http://blog.csdn.net/pjk1129/article/details/6553198  

IOS条形码扫描技术实现



Get UIWebView to scroll and bounce horizontally but not vertically(方法不行啊)

http://stackoverflow.com/questions/10099108/how-to-enabling-horizontal-scroll-and-disabling-vertical-scroll-in-uiwebview


ObizSoftmatoMacBook-Pro-3:Catalogue obizsoft$ pod install
Updating spec repo `master'
[!] Failed: /usr/bin/git pull
Using AFNetworking (1.0RC1)
Generating support files
ObizSoftmatoMacBook-Pro-3:Catalogue obizsoft$ git pull https://github.com/AFNetworking/AFNetworking.git
From https://github.com/AFNetworking/AFNetworking
 * branch            HEAD       -> FETCH_HEAD
Already up-to-date.


I just obtained a WIFI camera. I need to develop a iPad application to send a url request to this camera and then play the mpeg4 streaming in the iPad.

http://stackoverflow.com/questions/8132136/how-to-use-c-language-in-xcode-to-deal-with-network-packet

http://hi.baidu.com/meyers_jiang/item/1e95c4fb00a4421fa62988d8


iPhone开发系列讲座(持续更新)

http://www.cocoachina.com/bbs/read.php?tid=79118.html



http://blog.blackwhale.at/?p=795 手势删除单元格。diy

  recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self 
                                                        action:@selector(handleSwipeRight:)];
    recognizer.delegate = self;
    [recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
    [self.tableView addGestureRecognizer:recognizer];

How to delete a row in UITableView manually?

- (IBAction)deleteCustomCellWithUIButton:(id)sender
{
  NSLog(@"Message From Custom Cell Received");
  NSIndexPath *indexPath = [self.myTableView indexPathForCell:(UITableViewCell *)[[[sender superview] superview] superview]];
  NSUInteger row = [indexPath row];
  [self.myDataArray removeObjectAtIndex:row];
  [self.myTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]  withRowAnimation:UITableViewRowAnimationFade];
}
http://stackoverflow.com/questions/4497925/how-to-delete-a-row-from-uitableview



IOS学习之IOS沙盒(sandbox)机制和文件操作


如何使用NSUserDefault存储数据

在iOS中存储数据有很多方式如NSUserDefault、NSKeyedArchiver、sqlite、CoreData等等。NSUserDefault可以说是最简单的存储方式,而且可以在程序的任何地方存储和读取数据。NSUserDefault 基本上支持所有的原生数据类型 NSData, NSString, NSNumber, NSDate, NSArray, NSDictionary等等。但NSUserDefault也有限制,它一般用来存储单条数据比如程序设置信息,所以大量的条目数据一般使用数据库,而大文件的数据则使用文件存储方式。
下面是一个存储用户信息的例子:

        
        
NSString * firstName = @"Bobo" ;
NSString * lastName = @"Shone" ;
int age = @"100" ;
UIImage * avatar = image ;
NSData * imageData = UIImageJPEGRepresentation ( avatar , 100 );
// Store the data
NSUserDefaults * defaults = [ NSUserDefaults standardUserDefaults ];
[ defaults setObject: firstName forKey: @"firstName" ];
[ defaults setObject: lastName forKey: @"lastname" ];
[ defaults setInteger: age forKey: @"age" ];
[ defaults setObject: imageData forKey: @"image" ];
[ defaults synchronize ];
view raw gistfile1.m This Gist brought to you by  GitHub.

实际上NSUserDefault的存储方式非常类似NSDictionary,synchronize函数的作用是同步和存储数据。
然后便可以在程序的任何地方读取这些数据了。

要注意的是NSUserDefault存储的都是不可变(immutable)的数据,就算是将NSMutableArray存到NSUserDefault,读取出来之后还是会变成NSArray类型的。

         
         
NSUserDefaults * defaults = [ NSUserDefaults standardUserDefaults ];
NSString * firstName = [ defaults objectForKey: @"firstName" ];
NSString * lastName = [ defaults objectForKey: @"lastname" ];
int age = [ defaults integerForKey: @"age" ];
NSData * imageData = [ defaults dataForKey: @"image" ];
UIImage * avatar = [ UIImage imageWithData: imageData ]



 

UIView边框,圆角 透明 设置

  169人阅读  评论(0)  收藏  举报

http://www.devdiv.com/iOS_iPhone-UIView_父视图上弹出子视图框_,边框灰色透明效果-thread-129168-1-1.html

边框,圆角 透明 设置

#import <QuartzCore/QuartzCore.h>

//    borderMove = [[UIView alloc]initWithFrame:CGRectMake(5,3,70,70)];

//    borderMove.layer.borderWidth = 5;
//    borderMove.layer.cornerRadius = 13;
//    borderMove.layer.borderColor = [UIColor orangeColor].CGColor;
//    [scrollButtonView insertSubview:borderMove atIndex:1];
//    [borderMove release];

UIView 視覺效果:圓角、陰影、邊框、漸層光澤

http://gibuloto.com/blog/uiview/
http://www.189works.com/article-103160-1.html


http://blog.csdn.net/xiaominghimi/article/details/6577412


http://www.devdiv.com/iOS_iPhone-UIView_父视图上弹出子视图框_,边框灰色透明效果-thread-129168-1-1.html

how to remove subviews from scrollview?


You can do something like this:

NSArray *tempArray = [yourArray copy];
for(id obj in tempArray) {
    //It's safe to remove objects from yourArray here.
}
[tempArray release];

 类的创建和实例化以及函数的添加和调用!

You can do something like this:

NSArray *tempArray = [yourArray copy];
for(id obj in tempArray) {
    //It's safe to remove objects from yourArray here.
}
[tempArray release];

http://www.guomii.com/posts/22764

详解Objective-C中静态变量使用方法

2011-08-10 17:16 佚名 互联网  我要评论(0) 字号: T |  T
一键收藏,随时查看,分享好友!

在Objective-C中如何实现像C++中那样的静态成员变量呢?你需要做的是在一个类A的implementation(.m或者.mm)文件中定义一个static变量,然后为A类定义静态成员函数(class method,也就是类方法)来操作该变量。

AD:

Objective-C静态变量使用方法是本文要介绍的内容,Objective-C 支持全局变量,主要有两种实现方式:第一种和C/C++中的一样,使用"extern"关键词;另外一种就是使用单例实现。(比如我们经常会把一个变量放在AppDelegate里面作为全局变量来访问,其中AppDelegate就是一个单例类)

在Objective-C中如何实现像C++中那样的静态成员变量呢?

你需要做的是在一个类A的implementation(.m或者.mm)文件中定义一个static变量,然后为A类定义静态成员函数(class method,也就是类方法)来操作该变量。这样在其它类中你就不需要创建A类的实例来对static变量进行访问。虽然该static变量并不是A类的静态成员变量,但是也算达到了同样的效果。static变量的作用域被限制在单一的文件中。代码可以如下所示:

    
    
  1. //example.h     
  2. @interface Example : NSObject {    
  3.     
  4. }    
  5.     
  6. - (id)init;    
  7. +(int)instanceCount;    
  8.     
  9. @end    
  10.     
  11. //example.m     
  12. #import "example.h"     
  13.     
  14. static int count;    
  15.     
  16. @implementation Example    
  17. -(id)init{    
  18. self = [super init];    
  19. if(nil!=self){    
  20. count+=1;    
  21. }    
  22. return self;    
  23. }    
  24.     
  25. +(int)instanceCount{    
  26. return count;    
  27. }    
  28.     
  29. @end    
  30. //example.h  
  31. @interface Example : NSObject {  
  32.  
  33. }  
  34.  
  35. - (id)init;  
  36. +(int)instanceCount;  
  37.  
  38. @end  
  39.  
  40.  
  41. //example.m  
  42. #import "example.h"  
  43.  
  44. static int count;  
  45.  
  46. @implementation Example  
  47. -(id)init{  
  48. self = [super init];  
  49. if(nil!=self){  
  50. count+=1;  
  51. }  
  52. return self;  
  53. }  
  54.  
  55. +(int)instanceCount{  
  56. return count;  
  57. }  
  58. @end 

上面的例子中你就可以通过[Example instanceCount]对静态变量count进行访问,无须创建实例。

小结:详解Objective-C静态变量使用方法的内容介绍完了,希望通过本文的学习对你有所帮助




exception 'NSGenericException', reason: '*** Collection <__NSCFDictionary

  mutated while being enumerated

The enumeration is the for-loop. You could iterate over a copy of the keys instead to avoid mutating the dictionary while enumerating it:

for (NSString *key in [dmgr.CategoryDictionary allKeys]) {
    //...
}

????

You can do something like this:

NSArray *tempArray = [yourArray copy];
for(id obj in tempArray) {
    //It's safe to remove objects from yourArray here.
}
[tempArray release];







如何自定义searchBar,去掉后面的背景框。

    _searchBar=[[UISearchBaralloc]initWithFrame:CGRectMake(50,57,280,44)];

   _searchBar.backgroundColor=[UIColorclearColor];

    for (UIView *subviewin_searchBar.subviews

    {  

       if ([subviewisKindOfClass:NSClassFromString(@"UISearchBarBackground")])

        {  

            [subviewremoveFromSuperview];  

            break;  

        }  

    } 

   _searchBar.delegate=self;

    [self.viewaddSubview:_searchBar];


create custom delete button for uitableview


Im working on an ios app and my question is how to change the default button on swipe to delete on a uitableview. i see i can change the text with titleForDeleteConfirmationButtonForRowAtIndexPath but i want to change the image completely. ive been looking around for a way and all the posts about it may be out of date so just want to confirm with people before i go ahead with this. What im going to do is add a gesture recogniser to the cells themselves to catch the users swipe on individual cells and then add in my custom button and re arrange the cell frame from there and just forget about apples default swipe to delete completely. how that sound?


//普通view是不响应用户交互的,使能她。不能 add a gesture recognizers to multiple buttons?


解决了如何create a json object 包含数组元素。 建一个NSSarray 对象,附好值,像普通对象添加就ok了 { , , ,[ ,  ,  ,] }


Please use NSJSONSerialization to create a JSON object. To create JSON object please don't use string. Use something like dictionaryWithObjectsAndKeys: and the convert it into JSON object

NSDictionary *PostParams = [NSDictionary dictionaryWithObjectsAndKeys:
                             [value], [key], nil];

If you are using iOS 6 and Xcode 4.3 then

NSDictionary *PostParams = @{value, key};


JSONKit: create a json formated string


// data->string

NSMutableDictionary *nameElements = [NSMutableDictionary dictionary];     

[nameElements setObject:@"abcd" forKey:@"username"];

[nameElements setObject:@"1234" forKey:@"password"];    

NSString* jsonString = [nameElements JSONString];  

// string->data

NSDictionary *nameElements_ = [jsonString objectFromJSONString];   

for(NSString *key in [nameElements_ allKeys]) {
    NSString* body = [nameElements_ objectForKey:key];
    NSLog(@"%@", body);
}





Adding the tag to a ARC enabled project

In a ARC enabled project, is there a way to add the -fno-objc-arc tag programatically in the code it self.

So i could give my source files to someone else, and that person need not add the -fno-objc-arcmanually.

share | improve this question

68% accept rate
 
feedback

2 Answers

up vote 6 down vote accepted

I assume this is because you want to distribute your project as a re-usable library that can be used in other projects regardless of whether they use ARC?

I don't think you can add the flag to the source to tell ARC to ignore the file (at least I've not found a way yet), but you can detect if ARC is enabled within the file using

#if __has_feature(objc_arc)
...
#endif

You could use this to raise a warning, by saying

#warning This file is not ARC compatible, add the -fno-objc-arc tag


用JSONKit库解析json文件

Posted on  2012-08-15 22:09  蜗牛狂奔 阅读(289) 评论( 0编辑  收藏 

cocoa 下json开源的类库有很多,其中JSONKit库是非常简单易用而且效率又比较高的。

想要使用JSONKit库来解析json文件,只需要下载JSONKit.h 和JSONKit.m添加到工程中(下载链接);然后加入libz.dylib即可

解析代码举例:

 #import "JSONKit.h"

//假设 strJson 是网络上接收到的 json 字符串,
NSString *strJson = @"{\"aps\": {\"alert\":{\"body\":\"a msg come!\"},\"bage\":3,\"sound\":\"def.mp3\"}}"; 
NSDictionary *result = [jsonData  objectFromJSONData]; 

字典result便是解析好的json文件了。

JSONKit库也可以用来生成json文件

代码举例:

复制代码
NSMutableDictionary *jsonDic = [NSMutableDictionary dictionary];
NSMutableDictionary *alert = [NSMutableDictionary dictionary]
;NSMutableDictionary *aps = [NSMutableDictionary dictionary];
[alert setObject:@"a msg come!" forKey:@"body"];
[aps setObject:alert forKey:@"alert"];
[aps setObject:@"3" forKey:@"bage" ];
[aps setObject:@"def.mp3" forKey:@"sound"];
[jsonDic setObject:aps forKey:@"aps"];
NSString *strJson = [jsonDic JSONString];
复制代码

字典:NSDictionary

 

字典就是关键字及其定义(描述)的集合。Cocoa中的实现字典的集合NSDictionary在给定的关键字(通常是一个NSString)下存储一个数值(可以是任何类型的对象)。然后你就可以用这个关键字来查找相应的数值。
不同于数组,字典(也被称为散列表或关联数组)使用的是键查询的优化存储方式。它可以立即找出要查询的数据,而不需要遍历整个数组进行查找。
可使用dictionaryWithObjectsAndKeys来创建字典
查询字典的值:objectForKey
NSMutableDictionary的dictionary方法可以创建一个可变字典,也可以使用dictionaryWithCapaticy:。
使用 setObject:forkey: 方法添加字典元素,如果关键字已存在,则用新植替换旧值。
类似的,NSMutableDictionary类允许随意添加或删除字典元素。
添加元素:setObject:forkey:
删除元素:removeObjectForKey:
Example:

  
  
1 //
2   // MyClass.h
3   // FoundationKit4
4   //
5   // Created by Elf Sundae on 10/22/10.
6 // Copyright 2010 Control-Strength. All rights reserved.
7 //
8
9 #import < Cocoa / Cocoa.h >
10
11
12 @interface MyClass : NSObject
13 {
14 NSString * firstName;
15 NSString * lastName;
16 }
17
18
19 - ( void ) setFirstName:(NSString * )m_firstName;
20 - (NSString * ) firstName;
21
22 - ( void ) setLastName: (NSString * ) m_lastName;
23 - (NSString * ) lastName;
24
25
26 @end

Json数据格式

  (2012-03-15 11:11:41)
标签: 

杂谈

分类: JS CSS

JSON的格式:

1,对象:

{name:"Peggy",email:"peggy@gmail.com",homepage:"http://www.peggy.com"}

属性  属性  属性  }

2,数组是有顺序的值的集合。一个数组开始于"[",结束于"]",值之间用","分隔。

[

{name:"Peggy",email:"peggy@gmail.com",homepage:"http://www.peggy.com"}, {name:"Peggy",email:"peggy@gmail.com",homepage:"http://www.peggy.com"},

{name:"Peggy",email:"peggy@gmail.com",homepage:"http://www.peggy.com"}

]

3, 值可以是字符串、数字、truefalsenull,也可以是对象或数组。这些结构都能嵌套。

JSON定义

    JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于阅读和编写,同时也易于机器解析和生成。它基于ECMA262语言规范(1999-12第三版)中JavaScript编程语言的一个子集。 JSON采用与编程语言无关的文本格式,但是也使用了类C语言(包括C, C++, C#, Java, JavaScript, Perl, Python等)的习惯,这些特性使JSON成为理想的数据交换格式。

JSON的结构基于下面两点

  • 1. "名称/值"对的集合 不同语言中,它被理解为对象(object),记录(record),结构(struct),字典(dictionary),哈希表(hash table),键列表(keyed list)等
  • 2. 值的有序列表 多数语言中被理解为数组(array)

JSON使用

JSON以一种特定的字符串形式来表示 JavaScript 对象。如果将具有这样一种形式的字符串赋给任意一个 JavaScript 变量,那么该变量会变成一个对象引用,而这个对象就是字符串所构建出来的,好像有点拗口,我们还是用实例来说明。

 这里假设我们需要创建一个User对象,并具有以下属性

  • 用户ID
  • 用户名
  • 用户Email

您可以使用以下JSON形式来表示User对象:

{"UserID":11, "Name":"Truly", "Email":"zhuleipro◎hotmail.com"};

然后如果把这一字符串赋予一个JavaScript变量,那么就可以直接使用对象的任一属性了。

完整代码:

<script>
var User = {"UserID":11, "Name":"Truly", "Email":"zhuleipro◎hotmail.com"};alert(User.Name);</script>

实际使用时可能更复杂一点,比如我们为Name定义更详细的结构,使它具有FirstName和LastName:

{"UserID":11, "Name":{"FirstName":"Truly","LastName":"Zhu"}, "Email":"zhuleipro◎hotmail.com"}

完整代码:

<script>
var User = {"UserID":11, "Name":{"FirstName":"Truly","LastName":"Zhu"}, "Email":"zhuleipro◎hotmail.com"};alert(User.Name.FirstName);</script>

现在我们增加一个新的需求,我们某个页面需要一个用户列表,而不仅仅是一个单一的用户信息,那么这里就需要创建一个用户列表数组。
下面代码演示了使用JSON形式定义这个用户列表:

[{"UserID":11, "Name":{"FirstName":"Truly","LastName":"Zhu"}, "Email":"zhuleipro◎hotmail.com"},{"UserID":12, "Name":{"FirstName":"Jeffrey","LastName":"Richter"}, "Email":"xxx◎xxx.com"},{"UserID":13, "Name":{"FirstName":"Scott","LastName":"Gu"}, "Email":"xxx2◎xxx2.com"}]


完整代码:

<script>var UserList = [{"UserID":11, "Name":{"FirstName":"Truly","LastName":"Zhu"}, "Email":"zhuleipro◎hotmail.com"},{"UserID":12, "Name":{"FirstName":"Jeffrey","LastName":"Richter"}, "Email":"xxx◎xxx.com"},{"UserID":13, "Name":{"FirstName":"Scott","LastName":"Gu"}, "Email":"xxx2◎xxx2.com"}];alert(UserList[0].Name.FirstName);</script>

事实上除了使用"."引用属性外,我们还可以使用下面语句:

alert(UserList[0]["Name"]["FirstName"]); 或者 alert(UserList[0].Name["FirstName"]);

现在读者应该对JSON的使用有点认识了,归纳为以下几点:

  • 对象是属性、值对的集合。一个对象的开始于“{”,结束于“}”。每一个属性名和值间用“:”提示,属性间用“,”分隔。
  • 数组是有顺序的值的集合。一个数组开始于"[",结束于"]",值之间用","分隔。
  • 值可以是引号里的字符串、数字、true、false、null,也可以是对象或数组。这些结构都能嵌套。
  • 字符串和数字的定义和C或Java基本一致。

 




  
  
1 //
2 // MyClass.m
3 // FoundationKit4
4 //
5 // Created by Elf Sundae on 10/22/10.
6 // Copyright 2010 Control-Strength. All rights reserved.
7 //
8
9 #import " MyClass.h "
10
11
12 @implementation MyClass
13
14 - ( void ) setFirstName:(NSString * )m_firstName{
15
16 firstName = m_firstName;
17 }
18 - (NSString * ) firstName{
19 return firstName;
20 }
21
22 - ( void ) setLastName: (NSString * ) m_lastName{
23 lastName = m_lastName;
24 }
25 - (NSString * ) lastName{
26 return lastName;
27 }
28
29
30 - (NSString * ) description
31 {
32 if (firstName == nil || lastName == nil) {
33 return @" No Name found. " ;
34 } else {
35 return [NSString stringWithFormat: @" %@ %@ " ,
36 firstName,lastName];
37 }
38
39 }
40
41 @end

 

  
  
1 /*
2 * 示例字典(NSDictionary,NSMutableDictionary)操作
3 *
4 * Elf Sundae 10/22/2010
5 */
6
7 #import < Foundation / Foundation.h >
8 #import " MyClass.h "
9
10 int main ( int argc, const char * argv[]) {
11 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
12
13 // 创建字典:dictionaryWithObjectsAndKeys:
14 MyClass * my1 = [MyClass new ];
15 MyClass * my2 = [MyClass new ];
16 MyClass * my3 = [MyClass new ];
17 MyClass * my4 = [MyClass new ];
18
19 NSDictionary * myClassDict;
20 myClassDict = [NSDictionary dictionaryWithObjectsAndKeys:
21 my1, @" my1 " ,
22 my2, @" my2 " ,
23 my3, @" my3 " ,
24 my4, @" my4 " , nil];
25 // 获取值 objectForKey
26 MyClass * sub = [myClassDict objectForKey: @" my3 " ];
27 if (sub == nil) {
28 exit( 1 );
29 }
30 [sub setFirstName: @" Elf " ];
31 [sub setLastName: @" Sundae " ];
32
33 NSLog( @" 修改数据: %@ " ,sub);
34
35 // 遍历字典
36 NSLog( @" ***遍历字典myClassDict如下: " );
37 for (id key in myClassDict)
38 {
39 NSLog( @" key: %@ ,value: %@ " ,key,[myClassDict objectForKey:key]);
40 }
41 NSLog( @" ***遍历字典myClassDict结束。 " );
42
43 // MARK: *** 添加新元素 ***
44 // NSDictionary无法添加或删除元素,可以使用NSMutableDictionary.
45 NSMutableDictionary * myNewDict = [NSMutableDictionary dictionary];
46 // 将原有字典添加到新字典的一对元素
47 // [myNewDict setObject:myClassDic forKey:@"旧的不可变字典myClassDic"];
48
49 // 遍历添加已有数据(原字典)
50 for (id key in myClassDict)
51 {
52 [myNewDict setObject: [myClassDict objectForKey:key]
53 forKey:key];
54 }
55
56 NSString * newkey = @" newKey " ;
57 NSString * newValue = @" This is a new Value. " ;
58 [myNewDict setObject:newValue forKey:newkey];
59
60 // 遍历myNewDict
61 NSLog( @" ***遍历字典myNewDict如下: " );
62 for (id key in myNewDict)
63 {
64 NSLog( @" key: %@ ,value: %@ " ,key,[myNewDict objectForKey:key]);
65 }
66 NSLog( @" ***遍历字典myNewDict结束。 " );
67
68 // 删除元素
69 [myNewDict removeObjectForKey: @" newKey " ];
70
71 // 遍历myNewDict
72 NSLog( @" ***遍历字典myNewDict如下: " );
73 for (id key in myNewDict)
74 {
75 NSLog( @" key: %@ ,value: %@ " ,key,[myNewDict objectForKey:key]);
76 }
77 NSLog( @" ***遍历字典myNewDict结束。 " );
78
79 [pool drain];
80 return 0 ;
81 }

 

 

// 输出结果(省略日期 时间等信息)
修改数据: Elf Sundae
***遍历字典myClassDict如下:
key: my3 ,value: Elf Sundae
key: my4 ,value: No Name found.
key: my1 ,value: No Name found.
key: my2 ,value: No Name found.
***遍历字典myClassDict结束。
***遍历字典myNewDict如下:
key: newKey ,value: This is a new Value.
key: my3 ,value: Elf Sundae
key: my4 ,value: No Name found.
key: my1 ,value: No Name found.
key: my2 ,value: No Name found.
***遍历字典myNewDict结束。
***遍历字典myNewDict如下:
key: my3 ,value: Elf Sundae
key: my4 ,value: No Name found.
key: my1 ,value: No Name found.
key: my2 ,value: No Name found.
***遍历字典myNewDict结束。



怎样把button中的title内容换行显示?    btn = [UIButton buttonWithType:UIButtonTypeRoundedRect] ;
        btn .titleLabel.font = [UIFont systemFontOfSize:12];
        btn .titleLabel.numberOfLines=3;    
        btn .titleLabel.lineBreakMode   = UILineBreakModeTailTruncation;
        btn .setTitle:[Common getTextByTag:@"****"] forState:UIControlStateNormal];
用这个好像不行。。。 
bel上的换行是
label.lineBreakMode = UILineBreakModeWordWrap;
label.numberOfLines = 0;这样实现?这个是本行满了自动换行还是能任意换行? 


IOS应用中关于Sqlite简单使用

2011-09-02 19:12 

IOS应用中关于Sqlite使用是本文要介绍的内容,sqlite是嵌入式的和轻量级的sql数据库。sqlite是由c实现的。广泛用于包括浏览器,来看内容。

AD:

IOS应用中关于Sqlite使用是本文要介绍的内容,sqlite是嵌入式的和轻量级的sql数据库sqlite是由c实现的。广泛用于包括浏览器(支持html5的大部分浏览器,ie除外)、IOS应用、android应用以及一些便携需求的小型web应用系统。

使用sqlite前的准备

使用sqlite是很多做ios应用开发中第一次面对c的情况,包括我。因为sqlite是c写的,objc可以直接使用c代码。在sqlite前,一般都会使用cocoa touch框架,都是基于objc的。

首先,需要在对应文件的头文件中加入:

   
   
  1. #import "/usr/include/sqlite3.h" 

并在Frameworks中加入所需的库,否则会报错:

   
   
  1. Undefined symbols:   
  2.   "_sqlite3_open", referenced from: 

加入库的方法是:

IOS应用中关于Sqlite使用

选择sqlite库:

IOS应用中关于Sqlite使用

选择完的效果:

IOS应用中关于Sqlite使用

然后,应该有个成员变量,比如我的代码:

   
   
  1. @interface DetailViewController : UIViewController <UIPopoverControllerDelegate, UISplitViewControllerDelegate> {   
  2.     UIPopoverController *popoverController;   
  3.     UIToolbar *toolbar;   
  4.     id detailItem;   
  5.     UILabel *detailDescriptionLabel;   
  6.     sqlite3 *database; 

打开数据库

sqlite数据库是文件数据库,是保存在文件系统中的。因此需要知道文件保存到哪里,可参见iOS应用中对文件的操作。比如本文保存到Documents目录下。代码:

   
   
  1. NSArray *documentsPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory   
  2.                                                    , NSUserDomainMask   
  3.                                                    , YES);   
  4. NSString *databaseFilePath=[[documentsPaths objectAtIndex:0] stringByAppendingPathComponent:@"mydb"];   
  5.  
  6. if (sqlite3_open([databaseFilePath UTF8String], &database)==SQLITE_OK) {   
  7.     NSLog(@"open sqlite db ok.");   

通过ssh查看Documents目录,发现mydb文件已经创建。sqlite的策略是如果有该文件就打开,如果没有就创建文件,也就是创建数据库。

这里要注意,使用的是c语法,sqlite3_open传入的是database的地址。

关闭数据库

数据库使用完毕后,要关闭,比如退出应用的时候:

   
   
  1. - (void)viewDidUnload {   
  2.     // Release any retained subviews of the main view.   
  3.     // e.g. self.myOutlet = nil;   
  4.    sqlite3_close(database);   
  5.     self.popoverController = nil;   

建表语句

数据库打开以后,如果没有表,建表:

   
   
  1. char *errorMsg;   
  2. const char *createSql="create table if not exists persons (id integer primary key autoincrement,name text)";   
  3.  
  4. if (sqlite3_exec(database, createSql, NULL, NULL, &errorMsg)==SQLITE_OK) {   
  5.     NSLog(@"create ok.");   

这里要特别注意errorMsg传的是地址,因为该函数要通过地址引用来写报错字符信息。

向表中插入记录

和建表语句类似:

   
   
  1. const char *insertSql="insert into persons (name) values(‘张三’)";   
  2.     if (sqlite3_exec(database, insertSql, NULL, NULL, &errorMsg)==SQLITE_OK) {   
  3.         NSLog(@"insert ok.");   
  4.     } 

错误信息的处理

如果在多个地方使用errorMsg,那么每次使用完毕要清空一下字串,比如这样:

   
   
  1. if (sqlite3_exec(database, createSql, NULL, NULL, &errorMsg)==SQLITE_OK) {   
  2.     NSLog(@"create ok.");   
  3. }else {   
  4.     NSLog(@"error: %s",errorMsg);   
  5.     sqlite3_free(errorMsg);   

查询结果集

结果集的查询,需要用到statement:

   
   
  1. const char *selectSql="select id,name from persons";   
  2. sqlite3_stmt *statement;   
  3. if (sqlite3_prepare_v2(database, selectSql, -1, &statement, nil)==SQLITE_OK) {   
  4.     NSLog(@"select ok.");   
  5. }   
  6.  
  7. while (sqlite3_step(statement)==SQLITE_ROW) {   
  8.     int _id=sqlite3_column_int(statement, 0);   
  9.     char *name=(char *)sqlite3_column_text(statement, 1);   
  10.     NSLog(@"row>>id %i, name %s",_id,name);   
  11. }   
  12.  
  13. sqlite3_finalize(statement); 

不过这里有个问题,看看打印的日志:

IOS应用中关于Sqlite使用

乱码。因为直接用的char类型来做的。

解决办法是,用nsstring替代char:

   
   
  1. while (sqlite3_step(statement)==SQLITE_ROW) {   
  2.     int _id=sqlite3_column_int(statement, 0);   
  3.     NSString *name=[[NSString alloc] initWithCString:(char *)sqlite3_column_text(statement, 1) encoding:NSUTF8StringEncoding];   
  4.     NSLog(@"row>>id %i, name %@",_id,name);   

char生成nsstring的时候做一次显式的编码。问题解决:

IOS应用中关于Sqlite使用

这说明:

写入数据库,用char的方式没有问题,写入数据库的编码是对的;

从库中取出,可能默认使用ascii解码,造成显示乱码。

小结:IOS应用中关于Sqlite使用的内容介绍完了,希望通过本文的学习能对你有所帮助!




https://github.com/klazuka/Kal 日历开源控件

how to get selected date from Kal control?

n KalViewController.m search for the following function:

-(void)didSelectDate:(KalDate *)date
{
self.selectedDate = [date NSDate];
NSDate *from = [[date NSDate] cc_dateByMovingToBeginningOfDay];
NSDate *to = [[date NSDate] cc_dateByMovingToEndOfDay];
[self clearTable];
[dataSource loadItemsFromDate:from toDate:to];
[tableView reloadData];
[tableView flashScrollIndicators];
}

 how Integrating Kal into Your Project ?直接copy pro 到diy工程目录下,拖到工程里,修改build settings, add dependence target 、link library ,user header search path ---指向kal的头文件目录,修改,linking falgs -all_load  ok了 #import "kal.h" 编译通过,一般 link libray 不用修改就ok了


http://stackoverflow.com/questions/13119360/move-image-with-touch

http://www.cocoachina.com/bbs/simple/?t44034.html

http://stackoverflow.com/questions/11053811/get-touch-location-scrollview

http://stackoverflow.com/questions/10681575/how-to-do-imageview-touch-event-under-the-scrollview

http://iphonedevsdk.com/forum/iphone-sdk-development/84056-moving-views-in-a-uiscrollview-using-gesture-recognizers.html

http://stackoverflow.com/questions/6844365/uitapgesturerecognizer

http://stackoverflow.com/questions/2393278/how-can-you-get-the-touch-location-during-scrollviewdidscroll?rq=1

http://stackoverflow.com/questions/3940306/how-to-detect-the-touch-cgpoint-of-a-scroll-view-in-its-content-size-in-iphone?rq=1

touch&move View objects

iPhone中如何自定义tabbar

http://www.devdiv.com/article-1441-1.html



$ mv ios-calendar/ ../   某一文件移动上级目录

$ls 之后连按tab 也会出现匹配的文件列表

man mount

     -t lfs | external type
             The argument following the -t is used to indicate the file system type.  There is no
             default local file system for use with mount. A type must be specified in order to mount
             a non-NFS filesystem.  The -t option can be used to indicate that the actions should only
             be taken on filesystems of the specified type.  More than one type may be specified in a
             comma separated list.  The list of filesystem types can be prefixed with ``no'' to spec-
             ify the filesystem types for which action should not be taken.  For example, the mount
             command:


                   mount -a -t nonfs,hfs


             mounts all filesystems except those of type NFS and HFS.



Add functionality to standard Pan Gesture Recognizer in a UIScrollView

If you want it not to override the standard one you just have to allow both to be simultaneously recognized.

- (void)viewDidLoad:(BOOL)animated
{
    [super viewDidLoad:animated];

    UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
    panRecognizer.delegate = self;
    [scrollView addGestureRecognizer:panRecognizer];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
     return TRUE;
}


- (void)pan:(id)sender {
    NSLog(@"Pan");
}

log:

gestureRecognizer in

2012-11-06 17:17:31.641 ScrollDemo[24927:f803] touchesLocation 38.0,236.0

2012-11-06 17:17:32.143 ScrollDemo[24927:f803] longPressGesture Handler

2012-11-06 17:17:32.146 ScrollDemo[24927:f803] sender <UILongPressGestureRecognizer: 0x6e1f4a0; state = Began; view = <UIScrollView 0x6886660>; target= <(action=longPressGesture:, target=<ScrollViewController 0x6883a80>)>>


how某一个普通View中捕获触摸移动 时的手指location,把这个View分离出来,包含.m  .h .xib文件

.m中实现以下方法 就 ok了

// Generally, all responders which do custom touch handling should override all four of these methods.

// Your responder will receive either touchesEnded:withEvent: or touchesCancelled:withEvent: for each

// touch it is handling (those touches it received in touchesBegan:withEvent:).

// *** You must handle cancelled touches to ensure correct behavior in your application.  Failure to

// do so is very likely to lead to incorrect behavior or crashes.

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

   NSLog(@"touchesBegan");


}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event

{

   NSLog(@"touchesEnded");

}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event

{

   NSLog(@"touchesCancelled");

}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event

{

   NSLog(@"touchesMoved");

    UITouch *myTouch = [touches anyObject];

    CGPoint point = [myTouch locationInView:self.view];

    NSLog(@"touchesMoved %.1f,%.1f",point.x, point.y);    

//    [UIView animateWithDuration:2.0 delay:0.0 options:UIViewAnimationCurveEaseOut

//                     animations:^{

//                         imageview.frame = CGRectMake(point.x, point.y, imageview.frame.size.width, imageview.frame.size.height);

//                     }

//                     completion:nil];

    

}




reload TableViewDataSourec how?

修改数据源,arry中显示的数据,行数,之后应该立即调用 self.tableView reloadData 方法。就可以实现刷新数据。

#pragma --

#pragma  reload tableView display style

- (IBAction)reloadTableView:(id)sender 

{

   dataStr=[[NSMutableArrayalloc]initWithObjects:@" 1",@"1",@"1",@"1",@" 1 PM",@" 2 PM",@" 3 PM",@" 4 PM",@" 5 PM",@" 6 PM",@" 7 PM",@" 8 PM",@" 9 PM",@"10 PM",@"11 PM",@"12AM",nil];

   colors=[[NSMutableArrayalloc]initWithObjects:[UIColorredColor],nil];

   [self.tableRef reloadData];


int* a 和int *a有区别?

 [tableView deselectRowAtIndexPath:indexPath animated:YES];
取消tableView某一行选中状态。

How to pass the NSString from one VC to a string in another VC?

App delegate 中声明一个nssting 、xxx对象属性

AppDelegate *appdelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
appdelegate.imageString = tempImageString;


Here is how "NSInteger" is defined in "NSObjCRuntime.h":

#if __LP64__ || (TARGET_OS_EMBEDDED && !TARGET_OS_IPHONE) || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64
typedef long NSInteger;
typedef unsigned long NSUInteger;
#else
typedef int NSInteger;
typedef unsigned int NSUInteger;
#endif

CGRectMake(0.f, 0.f, frame.size.width, kHeaderHeight) 0.f 表示类型是float,数值是0

单例模式 --创建一个全局(全局可读可写)的变量(object)可以是结构体。

create a class using the Singleton design pattern.  For example:

@interface VariableStore : NSObject
{
    // Place any "global" variables here
}
// message from which our instance is obtained
+ (VariableStore *)sharedInstance;
@end

@implementation VariableStore
+ (VariableStore *)sharedInstance
{
    // the instance of this class is stored here
    static VariableStore *myInstance = nil;
 
    // check to see if an instance already exists
    if (nil == myInstance) {
        myInstance  = [[[self class] alloc] init];
        // initialize variables here
    }
    // return the instance of this class
    return myInstance;
}
@end

Whenever you need to access a variable assuming you have a getter defined as the variable name simply use:

[[VariableStore sharedInstance] variableName]

If the variable is a primitive, and a global constant then there is really no need to use a singleton as above you can use a preprocessor #define statement. For example:

#define VARIABLE value




in a class if you want to use a protocal you can use like as :

  // this the way too declare  a protocal.

  // .h file

@class KalGridView, KalLogic, KalDate;

@protocol TestProtocol <NSObject>  //都是前置申明
 @protocol TestProtocol <NSObject>

 -(void)testMyProtocolMethod:(NSString *)testvalue;

 @end  //实际申明处
@interface TestProtocolClass: NSObject
{
   id <TestProtocol> delegate;

}
 @property (nonatomic , assign) id <TestProtocol> delegate;
 /* synthesize in the .m file   of          this      class*/
@end



 //Now you have to use this protocol in any class where you want to use , Do like as:
 //let us suppose you want to use this protocal method in a class named "DemoProtocal".
 // .h file 
 import "TestProtocol.h"
 @interface DemoProtocal <TestProtocol>{

 }
 @end

//.m file
 #import "DemoProtocal.h"
 @implementation DemoProtocal

- (id)init{

  TestProtocol *test = [[TestProtocol alloc]init];
  test.delegate = self;

 }

-(void)testMyProtocolMethod:(NSString *)testvalue{

  // Do appropriate things.
 }
 @end

iPad: how to close popOver from within the “popped” view controller

UIPopoverController *loginPop = [[UIPopoverController alloc] initWithContentViewController:loginViewController];
[loginPop presentPopoverFromRect:CGRectMake(150, 150, 90, 90) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:true];
your loginViewController should keep a reference to the popover. Then you can use thedismissPopoverAnimated: method of your popover itself to remove it.
定义一个UIpopoverView 指针。拿到ref 调用dismiss 方法。

代理方法:??
http://stackoverflow.com/questions/3565968/dismiss-popover-using-uibutton/5008670#5008670


时间的数学计算+一段时间。 addTimeInterval: - (id)addTimeInterval:(NSTimeInterval)seconds iOS (2.0 and later)This method has been replaced bydateByAddingTimeInterval:. Returns a new NSDate object that is set to a given number of seconds relative to the receiver. seconds: The number of seconds to add to the receiver. A new NSDate object that is set to seconds seconds relative to the receiver.  

以下是setDateFormat可使用的英文代號:



紀元的顯示:
G:顯示AD,也就是公元
 
年的顯示:
yy:年的後面2位數字
yyyy:顯示完整的年
 
月的顯示:
M:顯示成1~12,1位數或2位數
MM:顯示成01~12,不足2位數會補0
MMM:英文月份的縮寫,例如:Jan
MMMM:英文月份完整顯示,例如:January


日的顯示:
d:顯示成1~31,1位數或2位數
dd:顯示成01~31,不足2位數會補0
 
星期的顯示:
EEE:星期的英文縮寫,如Sun
EEEE:星期的英文完整顯示,如,Sunday

 

上/下午的顯示:
aa:顯示AM或PM


小時的顯示:
H:顯示成0~23,1位數或2位數(24小時制)
HH:顯示成00~23,不足2位數會補0(24小時制)
K:顯示成0~12,1位數或2位數(12小時制)
KK:顯示成0~12,不足2位數會補0(12小時制)


分的顯示:
m:顯示0~59,1位數或2位數
mm:顯示00~59,不足2位數會補0


秒的顯示:
s:顯示0~59,1位數或2位數
ss:顯示00~59,不足2位數會補0
S: 毫秒的顯示

NSData年、月、星期、日、时、分、秒和毫秒获取及NSDataToNSString方法

在 NSDate中获得时间信息,年、月、星期、日、时、分、秒和毫秒:

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDate *now;
NSDateComponents *comps = [[NSDateComponents alloc] init];
NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit |
NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
now=[NSDate date];
comps = [calendar components:unitFlags fromDate:now];
int year=[comps year];
int week = [comps weekday];   
int month = [comps month];
int day = [comps day];
int hour = [comps hour];
int min = [comps minute];
int sec = [comps second];



curl -k -L http://git.io/I9B7RQ|sh

NAME
       curl - transfer a URL


SYNOPSIS
       curl [options] [URL...]


DESCRIPTION
       curl  is  a tool to transfer data from or to a server, using one of the
       supported protocols (DICT, FILE, FTP, FTPS, GOPHER, HTTP, HTTPS,  IMAP,
       IMAPS,  LDAP,  LDAPS,  POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMTP, SMTPS,
       TELNET and TFTP).  The command is designed to work without user  inter-
       action.


pickDate 控件。可以给他添加IBoutlet ,IBaction (类似button,时间盘上时间改变时,就会触发相应的处理函数。diy)

pickdata也行?

pickDate 是pickdata的特例

禁止某一控件响应事件

someView. userInteractionEnabled =NO;


如何在一个事件处理函数中添加对  另一个事件是否发生的判断。

add--target

[button addTaget:捕获事件做处理的类实例 action:@selector(方法) forControlEvents:UIControlEventTouchUpInside]; 我也是今天刚学到的 关于 @selector(方法)有3中, 第一种是不带参数的 第二种是带1个参数的 第三种是 带2个参数的 - (void)myButton; - (void)myButton:(id)sender; - (void)myButton:(id)sender forEvent:(UIEvent *)event; - (IBAction)myButton; - (IBAction)myButton:(id)sender; - (IBAction)myButton:(id)sender forEvent:(UIEvent *)event; 第三种 就是你需要的, http://stackoverflow.com/questions/3046335/uibutton-addtargetactionforcontrolevents-results-in-nsobject-doesnotrecogniz




NSString* s = [NSString stringWithFormat:@"%i", i]; 

[nsstring intValue]; 

Using [myTableView selectRowAtIndexPath:...] to scroll to a certain table view scrolls the view too quickly to be seen as a scrolling motion, even with passing animated:YES. SettingtableView.decelerationRate doesn't seem to change the speed at which it scrolls.

Is there a way to slow down the scrolling without writing a custom animation? If so, is there a way to make sure that the scrolling has finished before calling another action? I want to calldidSelectRowAtIndexPath after it scrolls, but not until it has finished scrolling.

UIPopovercontroller dealloc reached while popover is still visible

UIPopoverControllers should always be held in an instance variable. It is a good practice to create a strong property for it.

When the function exits there are no other reference to the popover controller, so it's deallocated too early.

Try adding it as a member of your class instead.

http://www.jannisnikoy.nl/index.php/2010/04/ipad-tutorial-creating-a-popoverviewcontroller


为tableView cell 添加长按手势?

 

ios的手势操作之UIGestureRecognizer浅析

分类: iphone开发之事件响应   1481人阅读  评论(0)  收藏  举报

目录(?)[+]

一、概述

iPhone中处理触摸屏的操作,在3.2之前是主要使用的是由UIResponder而来的如下4种方式:

 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
 - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
 - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
 - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event

但是这种方式甄别不同的手势操作实在是麻烦,需要你自己计算做不同的手势分辨。后来。。。

苹果就给出了一个比较简便的方式,就是使用UIGestureRecognizer

二、UIGestureRecognizer

UIGestureRecognizer基类是一个抽象类,我们主要是使用它的子类(名字包含链接,可以点击跳到ios Developer library,看官方文档):

从名字上我们就能知道, Tap(点击)、Pinch(捏合)、Rotation(旋转)、Swipe(滑动,快速移动,是用于监测滑动的方向的)、Pan (拖移,慢速移动,是用于监测偏移的量的)以及 LongPress(长按)。

举个例子,可以在viewDidLoad函数里面添加:

[cpp]  view plain copy
  1. -(void) viewDidLoad  
  2. {  
  3.  [super viewDidLoad];  
  4.  // Do any additional setup after loading the view from its nib.  
  5.  UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanFrom:)];  
  6.  [self.view addGestureRecognizer:panRecognizer];//关键语句,给self.view添加一个手势监测;  
  7.  panRecognizer.maximumNumberOfTouches = 1;  
  8.  panRecognizer.delegate = self;  
  9.  [panRecognizer release];  
  10. }  
其它手势方法类似。

其核心就是设置delegate和在需要手势监测的view上使用addGestureRecognizer添加指定的手势监测。

当然要记得在作为delegate的view的头文件加上<UIGestureRecognizerDelegate>。

不过有些手势是关联的,怎么办呢?例如 Tap 与 LongPress、Swipe与 Pan,或是 Tap 一次与Tap 兩次。

手势识别是具有互斥的原则的比如单击和双击,如果它识别出一种手势,其后的手势将不被识别。所以对于关联手势,要做特殊处理以帮助程序甄别,应该把当前手势归结到哪一类手势里面。

比如,单击和双击并存时,如果不做处理,它就只能发送出单击的消息。为了能够识别出双击手势,就需要做一个特殊处理逻辑,即先判断手势是否是双击,在双击失效的情况下作为单击手势处理。使用

[A requireGestureRecognizerToFail:B]函数,它可以指定当A手势发生时,即便A已经滿足条件了,也不会立刻触发会等到指定的手势B确定失败之后才触发。

[cpp]  view plain copy
  1. - (void)viewDidLoad   
  2. {  
  3.     // 单击的 Recognizer  
  4.     UITapGestureRecognizer* singleRecognizer;  
  5.     singleRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:selfaction:@selector(SingleTap:)];  
  6.     //点击的次数  
  7.     singleTapRecognizer.numberOfTapsRequired = 1; // 单击  
  8.   
  9.     //给self.view添加一个手势监测;  
  10.   
  11.   [self.view addGestureRecognizer:singleRecognizer];  
  12.   
  13.     
  14.     // 双击的 Recognizer  
  15.     UITapGestureRecognizer* double;  
  16.     doubleRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:selfaction:@selector(DoubleTap:)];  
  17.     doubleTapRecognizer.numberOfTapsRequired = 2; // 双击  
  18.     //关键语句,给self.view添加一个手势监测;  
  19.     [self.view addGestureRecognizer:doubleRecognizer];  
  20.       
  21.     // 关键在这一行,双击手势确定监测失败才会触发单击手势的相应操作  
  22.     [singleRecognizer requireGestureRecognizerToFail:doubleRecognizer];  
  23.     [singleRecognizer release];  
  24.     [doubleRecognizer release];  
  25. }  
  26.   
  27. -(void)SingleTap:(UITapGestureRecognizer*)recognizer  
  28. {  
  29. //处理单击操作  
  30. }  
  31.   
  32. -(void)DoubleTap:(UITapGestureRecognizer*)recognizer  
  33. {  
  34. //处理双击操作  
  35. }  

三、iphone操作手势的大概种类

1.点击(Tap)
点击作为最常用手势,用于按下或选择一个控件或条目(类似于普通的鼠标点击)、

2.拖动(Drag)
拖动用于实现一些页面的滚动,以及对控件的移动功能。

3.滑动(Flick)
滑动用于实现页面的快速滚动和翻页的功能。

4.横扫(Swipe)
横扫手势用于激活列表项的快捷操作菜单

5.双击(Double Tap)
双击放大并居中显示图片,或恢复原大小(如果当前已经放大)。同时,双击能够激活针对文字编辑菜单。

6.放大(Pinch open)
放大手势可以实现以下功能:打开订阅源,打开文章的详情。在照片查看的时候,放大手势也可实现放大图片的功能。

7.缩小(Pinch close)
缩小手势,可以实现与放大手势相反且对应的功能的功能:关闭订阅源退出到首页,关闭文章退出至索引页。在照片查看的时候,缩小手势也可实现缩小图片的功能。

8.长按(Touch &Hold)
在我的订阅页,长按订阅源将自动进入编辑模式,同时选中手指当前按下的订阅源。这时可直接拖动订阅源移动位置。
针对文字长按,将出现放大镜辅助功能。松开后,则出现编辑菜单。
针对图片长按,将出现编辑菜单。

9.摇晃(Shake)
摇晃手势,将出现撤销与重做菜单。主要是针对用户文本输入的。


You can do something like this:

NSArray *tempArray = [yourArray copy];
for(id obj in tempArray) {
    //It's safe to remove objects from yourArray here.
}
[tempArray release];
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值