简体   繁体   English

返回类型类对象的方法

[英]method with return type class object

Write a method with 用写方法

return type MyClass object and with multiple parameter 返回类型MyClass对象并带有多个参数

i tried 我试过了

-(MyClass *Obj)mymethod:(NSString*)name withAge:(int)age
{
//do stuff
Obj.name=name;
Obj.age=age;
return Obj;
}

In some other class where i want to call this above function ,how i call it? 在其他我想调用上述函数的类中,我怎么称呼它呢?

You can write the method like: 您可以编写如下方法:

 -(MYClass *)myMEthod:(NSString *) name withAge:(int)age
   {
         MYClass *myObj=[[MYClass alloc]init];
         myObj.name=name;
         myObj.age=age;

        return myObj;
    }

If you want it to be singleton, then use static object and dispatch_once 如果希望它是单例,则使用静态对象和dispatch_once

TO make this a singleton: 要使它单例:

 +(MYClass *)myMEthod:(NSString *) name withAge:(int)age
   {
        static MYClass *_myObj=nil;

        static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _myObj = [[MYClass alloc]init];
    });
          _myObj.name=name;
          _myObj.age=age;
        return _myObj;

    }

And in other class, you can simply import this class, and call it by 在其他类中,您可以简单地导入此类,并通过

  [MYClass myMethod:@"" withAge:12];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法使用自定义类返回类型覆盖方法 - Cannot override method with a custom class return type 如何基于类类型返回对象? - How to return an object base on class type? 方法签名返回值“类型或子类类的类” - Method signature return value “Class of type or subclass class” 如何将方法的返回类型编写为符合协议的 class + swift - How to write a return type of a method as a class that conforms to a protocol + swift 找不到类方法“ + configureWithApplicationID:”(返回类型默认为“ id”) - class method '+configureWithApplicationID:' not found (return type defaults to 'id') 如何从类方法返回自定义的Objective-C对象? - How to Return a Custom Objective-C Object from a Class Method? 在“类”类型的对象上找不到字典元素的预期方法 - Expected method to read dictionary element not found on object of type “class” 从iPhone和Cocos2d中的类类型(+)方法访问对象? - Accessing an Object from Class type(+) method in iPhone & Cocos2d? 当通过类方法获取对象时,为什么在返回值之前,该方法可以将值放入AutoReleasePool中? - When via a class method get an object, why before return the value, the method can put the value into AutoReleasePool? 类方法返回不同的值 - Class method return distinct values
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM